From 46f7bbaaf53a7fd010c098caca1b4af2257b2053 Mon Sep 17 00:00:00 2001 From: Scott Erickson Date: Mon, 8 Dec 2014 14:21:40 -0800 Subject: [PATCH] Fixed client tests. Also updated mock-ajax to the latest version, carrying over my own tweaks. --- app/assets/javascripts/mock-ajax.js | 328 ---------- app/core/ModuleLoader.coffee | 1 + app/views/TestView.coffee | 27 +- .../component/ThangComponentsEditView.coffee | 4 - config.coffee | 12 +- test/app/{lib => core}/deltas.spec.coffee | 2 +- .../FacebookHandler.spec.coffee | 2 +- test/app/{lib => core}/utils.spec.coffee | 2 +- test/app/lib/LevelLoader.spec.coffee | 2 +- test/app/models/CocoModel.spec.coffee | 10 +- test/app/models/SuperModel.spec.coffee | 2 +- .../{modal => core}/AuthModal.spec.coffee | 6 +- .../ThangComponentsEditView.spec.coffee | 1 - .../editor/level/EditorLevelView.spec.coffee | 2 +- .../views/play/ladder/LadderTabView.coffee | 4 +- vendor/scripts/jasmine-boot.js | 176 +++++ .../scripts}/jasmine-html.js | 0 vendor/scripts/jasmine-mock-ajax.js | 609 ++++++++++++++++++ .../javascripts => vendor/scripts}/jasmine.js | 0 19 files changed, 819 insertions(+), 371 deletions(-) delete mode 100644 app/assets/javascripts/mock-ajax.js rename test/app/{lib => core}/deltas.spec.coffee (94%) rename test/app/{lib => core/social-handlers}/FacebookHandler.spec.coffee (97%) rename test/app/{lib => core}/utils.spec.coffee (98%) rename test/app/views/{modal => core}/AuthModal.spec.coffee (71%) create mode 100755 vendor/scripts/jasmine-boot.js rename {app/assets/javascripts => vendor/scripts}/jasmine-html.js (100%) create mode 100644 vendor/scripts/jasmine-mock-ajax.js rename {app/assets/javascripts => vendor/scripts}/jasmine.js (100%) diff --git a/app/assets/javascripts/mock-ajax.js b/app/assets/javascripts/mock-ajax.js deleted file mode 100644 index e4b75ed7b..000000000 --- a/app/assets/javascripts/mock-ajax.js +++ /dev/null @@ -1,328 +0,0 @@ -/* - -Jasmine-Ajax : a set of helpers for testing AJAX requests under the Jasmine -BDD framework for JavaScript. - -http://github.com/pivotal/jasmine-ajax - -Jasmine Home page: http://pivotal.github.com/jasmine - -Copyright (c) 2008-2013 Pivotal Labs - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - -*/ - -(function() { - function extend(destination, source, propertiesToSkip) { - propertiesToSkip = propertiesToSkip || []; - for (var property in source) { - if (!arrayContains(propertiesToSkip, property)) { - destination[property] = source[property]; - } - } - return destination; - } - - function arrayContains(arr, item) { - for (var i = 0; i < arr.length; i++) { - if (arr[i] === item) { - return true; - } - } - return false; - } - - function MockAjax(global) { - var requestTracker = new RequestTracker(), - stubTracker = new StubTracker(), - realAjaxFunction = global.XMLHttpRequest, - mockAjaxFunction = fakeRequest(requestTracker, stubTracker); - - this.install = function() { - global.XMLHttpRequest = mockAjaxFunction; - }; - - this.uninstall = function() { - global.XMLHttpRequest = realAjaxFunction; - - this.stubs.reset(); - this.requests.reset(); - }; - - this.stubRequest = function(url, data) { - var stub = new RequestStub(url, data); - stubTracker.addStub(stub); - return stub; - }; - - this.withMock = function(closure) { - this.install(); - try { - closure(); - } finally { - this.uninstall(); - } - }; - - this.requests = requestTracker; - this.stubs = stubTracker; - } - - function StubTracker() { - var stubs = []; - - this.addStub = function(stub) { - stubs.push(stub); - }; - - this.reset = function() { - stubs = []; - }; - - this.findStub = function(url, data) { - for (var i = stubs.length - 1; i >= 0; i--) { - var stub = stubs[i]; - if (stub.matches(url, data)) { - return stub; - } - } - }; - } - - function fakeRequest(requestTracker, stubTracker) { - function FakeXMLHttpRequest() { - requestTracker.track(this); - this.requestHeaders = {}; - } - - var iePropertiesThatCannotBeCopied = ['responseBody', 'responseText', 'responseXML', 'status', 'statusText', 'responseTimeout']; - extend(FakeXMLHttpRequest.prototype, new window.XMLHttpRequest(), iePropertiesThatCannotBeCopied); - extend(FakeXMLHttpRequest.prototype, { - open: function() { - this.method = arguments[0]; - this.url = arguments[1]; - this.username = arguments[3]; - this.password = arguments[4]; - this.readyState = 1; - this.onreadystatechange(); - }, - - setRequestHeader: function(header, value) { - this.requestHeaders[header] = value; - }, - - abort: function() { - this.readyState = 0; - this.status = 0; - this.statusText = "abort"; - this.onreadystatechange(); - }, - - readyState: 0, - - onload: function() { - }, - - onreadystatechange: function(isTimeout) { - }, - - status: null, - - send: function(data) { - this.params = data; - this.readyState = 2; - this.onreadystatechange(); - - var stub = stubTracker.findStub(this.url, data); - if (stub) { - this.response(stub); - } - }, - - data: function() { - var data = {}; - if (typeof this.params !== 'string') { return data; } - var params = this.params.split('&'); - - for (var i = 0; i < params.length; ++i) { - var kv = params[i].replace(/\+/g, ' ').split('='); - var key = decodeURIComponent(kv[0]); - data[key] = data[key] || []; - data[key].push(decodeURIComponent(kv[1])); - } - return data; - }, - - getResponseHeader: function(name) { - return this.responseHeaders[name]; - }, - - getAllResponseHeaders: function() { - var responseHeaders = []; - for (var i in this.responseHeaders) { - if (this.responseHeaders.hasOwnProperty(i)) { - responseHeaders.push(i + ': ' + this.responseHeaders[i]); - } - } - return responseHeaders.join('\r\n'); - }, - - responseText: null, - - response: function(response) { - this.status = response.status; - this.statusText = response.statusText || ""; - this.responseText = response.responseText || ""; - this.readyState = 4; - this.responseHeaders = response.responseHeaders || - {"Content-type": response.contentType || "application/json" }; - - this.onload(); - this.onreadystatechange(); - }, - - responseTimeout: function() { - this.readyState = 4; - jasmine.clock().tick(30000); - this.onreadystatechange('timeout'); - } - }); - - return FakeXMLHttpRequest; - } - - function RequestTracker() { - var requests = []; - - this.track = function(request) { - requests.push(request); - }; - - this.first = function() { - return requests[0]; - }; - - this.count = function() { - return requests.length; - }; - - this.reset = function() { - requests = []; - }; - - this.mostRecent = function() { - return requests[requests.length - 1]; - }; - - this.at = function(index) { - return requests[index]; - }; - - this.all = function() { - return requests.slice(0); - }; - - this.filter = function(url_to_match) { - if (requests.length == 0) return []; - var matching_requests = []; - - for (var i = 0; i < requests.length; i++) { - if (url_to_match instanceof RegExp && - url_to_match.test(requests[i].url)) { - matching_requests.push(requests[i]); - } else if (url_to_match instanceof Function && - url_to_match(requests[i])) { - matching_requests.push(requests[i]); - } else { - if (requests[i].url == url_to_match) { - matching_requests.push(requests[i]); - } - } - } - - return matching_requests; - }; - - this.sendResponses = function(responseMap) { - var urls = Object.keys(responseMap); - var success = true; - for(var i in urls) { - var url = urls[i]; - var responseBody = responseMap[url]; - var responded = false; - - var requests = jasmine.Ajax.requests.all().slice(); - for(var j in requests) { - var request = requests[j]; - if(request.url.startsWith(url)) { - request.response({status: 200, responseText: JSON.stringify(responseBody)}); - responded = true; - break; - } - } - if(!responded) { - var allRequests = jasmine.Ajax.requests.all(); - urls = []; - for(var k in allRequests) urls.push(allRequests[k].url); - console.error('could not find response for', url, 'in', urls, allRequests); - success = false; - continue; - } - } - return success; - } - } - - function RequestStub(url, stubData) { - var split = url.split('?'); - this.url = split[0]; - - var normalizeQuery = function(query) { - return query ? query.split('&').sort().join('&') : undefined; - }; - - this.query = normalizeQuery(split[1]); - this.data = normalizeQuery(stubData); - - this.andReturn = function(options) { - this.status = options.status || 200; - - this.contentType = options.contentType; - this.responseText = options.responseText; - }; - - this.matches = function(fullUrl, data) { - var urlSplit = fullUrl.split('?'), - url = urlSplit[0], - query = urlSplit[1]; - return this.url === url && this.query === normalizeQuery(query) && (!this.data || this.data === normalizeQuery(data)); - }; - } - - if (typeof window === "undefined" && typeof exports === "object") { - exports.MockAjax = MockAjax; - jasmine.Ajax = new MockAjax(exports); - } else { - window.MockAjax = MockAjax; - jasmine.Ajax = new MockAjax(window); - } -}()); - diff --git a/app/core/ModuleLoader.coffee b/app/core/ModuleLoader.coffee index c3be5aa65..f11a5591d 100644 --- a/app/core/ModuleLoader.coffee +++ b/app/core/ModuleLoader.coffee @@ -20,6 +20,7 @@ module.exports = ModuleLoader = class ModuleLoader extends CocoClass wrapped = _.wrap window.require, (func, name, loaderPath) -> # vendor libraries aren't actually wrapped with common.js, so short circuit those requires return {} if _.string.startsWith(name, 'vendor/') + return {} if name is 'tests' name = 'core/auth' if name is 'lib/auth' # proxy for iPad until it's been updated to use the new, refactored location. TODO: remove this return func(name, loaderPath) _.extend wrapped, window.require # for functions like 'list' diff --git a/app/views/TestView.coffee b/app/views/TestView.coffee index e49878a92..6e05509c6 100644 --- a/app/views/TestView.coffee +++ b/app/views/TestView.coffee @@ -1,11 +1,14 @@ -CocoView = require 'views/core/CocoView' +RootView = require 'views/core/RootView' template = require 'templates/test' requireUtils = require 'lib/requireUtils' +require 'vendor/jasmine-bundle' +require 'tests' + TEST_REQUIRE_PREFIX = 'test/app/' TEST_URL_PREFIX = '/test/' -module.exports = TestView = class TestView extends CocoView +module.exports = TestView = class TestView extends RootView id: 'test-view' template: template reloadOnClose: true @@ -16,24 +19,8 @@ module.exports = TestView = class TestView extends CocoView constructor: (options, @subPath='') -> super(options) @subPath = @subPath[1..] if @subPath[0] is '/' - @loadTestingLibs() - - loadTestingLibs: -> - @queue = new createjs.LoadQueue() unless @queue - @queue.on('complete', @scriptsLoaded, @) - @queue.on('fileload', @onFileLoad, @) - for f in ['jasmine', 'jasmine-html', 'boot', 'mock-ajax', 'test-app'] - if f not in @loadedFileIDs - @queue.loadFile({ - id: f - src: "/javascripts/#{f}.js" - type: createjs.LoadQueue.JAVASCRIPT - }) - - onFileLoad: (e) -> - @loadedFileIDs.push e.item.id if e.item.id - - scriptsLoaded: -> + + afterInsert: -> @initSpecFiles() @render() TestView.runTests(@specFiles) diff --git a/app/views/editor/component/ThangComponentsEditView.coffee b/app/views/editor/component/ThangComponentsEditView.coffee index 344815b57..a95326a14 100644 --- a/app/views/editor/component/ThangComponentsEditView.coffee +++ b/app/views/editor/component/ThangComponentsEditView.coffee @@ -36,10 +36,6 @@ DEFAULT_COMPONENTS = Mark: [] Item: [LC('Item')] -class ItemThangTypeSearchCollection extends CocoCollection - url: '/db/thang.type?view=items&project=original,name,version,slug,kind,components' - model: ThangType - module.exports = class ThangComponentsEditView extends CocoView id: 'thang-components-edit-view' template: template diff --git a/config.coffee b/config.coffee index a6bdd7f22..0c9eb3081 100644 --- a/config.coffee +++ b/config.coffee @@ -76,7 +76,7 @@ exports.config = #- vendor.js, all the vendor libraries 'javascripts/vendor.js': [ - regJoin('^vendor/scripts/(?!(Box2d|coffeescript|difflib|diffview))') + regJoin('^vendor/scripts/(?!(Box2d|coffeescript|difflib|diffview|jasmine))') regJoin('^bower_components/(?!(aether|d3|treema))') 'bower_components/treema/treema-utils.js' ] @@ -102,15 +102,23 @@ exports.config = 'javascripts/app/vendor/difflib.js': 'vendor/scripts/difflib.js' 'javascripts/app/vendor/diffview.js': 'vendor/scripts/diffview.js' 'javascripts/app/vendor/treema.js': 'bower_components/treema/treema.js' + 'javascripts/app/vendor/jasmine-bundle.js': regJoin('^vendor/scripts/jasmine') #- test, demo libraries - 'javascripts/test-app.js': regJoin('^test/app/') + 'javascripts/app/tests.js': regJoin('^test/app/') 'javascripts/demo-app.js': regJoin('^test/demo/') #- More output files are generated at the below order: before: [ + # jasmine-bundle.js ordering + 'vendor/scripts/jasmine.js' + 'vendor/scripts/jasmine-html.js' + 'vendor/scripts/jasmine-boot.js' + 'vendor/scripts/jasmine-mock-ajax.js' + + # vendor.js ordering 'bower_components/jquery/dist/jquery.js' 'bower_components/lodash/dist/lodash.js' 'bower_components/backbone/backbone.js' diff --git a/test/app/lib/deltas.spec.coffee b/test/app/core/deltas.spec.coffee similarity index 94% rename from test/app/lib/deltas.spec.coffee rename to test/app/core/deltas.spec.coffee index e658f3869..a08e433cf 100644 --- a/test/app/lib/deltas.spec.coffee +++ b/test/app/core/deltas.spec.coffee @@ -1,4 +1,4 @@ -deltas = require 'lib/deltas' +deltas = require 'core/deltas' describe 'deltas lib', -> diff --git a/test/app/lib/FacebookHandler.spec.coffee b/test/app/core/social-handlers/FacebookHandler.spec.coffee similarity index 97% rename from test/app/lib/FacebookHandler.spec.coffee rename to test/app/core/social-handlers/FacebookHandler.spec.coffee index 5084800c1..6f896d3eb 100644 --- a/test/app/lib/FacebookHandler.spec.coffee +++ b/test/app/core/social-handlers/FacebookHandler.spec.coffee @@ -1,4 +1,4 @@ -FacebookHandler = require 'lib/FacebookHandler' +FacebookHandler = require 'core/social-handlers/FacebookHandler' mockAuthEvent = response: diff --git a/test/app/lib/utils.spec.coffee b/test/app/core/utils.spec.coffee similarity index 98% rename from test/app/lib/utils.spec.coffee rename to test/app/core/utils.spec.coffee index bb1ab7233..048744eb4 100644 --- a/test/app/lib/utils.spec.coffee +++ b/test/app/core/utils.spec.coffee @@ -1,5 +1,5 @@ describe 'Utility library', -> - util = require 'lib/utils' + util = require 'core/utils' describe 'i18n', -> beforeEach -> diff --git a/test/app/lib/LevelLoader.spec.coffee b/test/app/lib/LevelLoader.spec.coffee index f177c703f..b7416abf5 100644 --- a/test/app/lib/LevelLoader.spec.coffee +++ b/test/app/lib/LevelLoader.spec.coffee @@ -119,7 +119,7 @@ describe 'LevelLoader', -> # first load Tharin by the 'normal' session load responses = '/db/level/id': levelWithOgreWithMace jasmine.Ajax.requests.sendResponses(responses) - responses = '/db/level_session/id': sessionWithTharinWithHelmet + responses = '/db/level.session/id': sessionWithTharinWithHelmet jasmine.Ajax.requests.sendResponses(responses) # then try to load Tharin some more diff --git a/test/app/models/CocoModel.spec.coffee b/test/app/models/CocoModel.spec.coffee index 0cce0b1cd..ff9181a97 100644 --- a/test/app/models/CocoModel.spec.coffee +++ b/test/app/models/CocoModel.spec.coffee @@ -1,5 +1,5 @@ CocoModel = require 'models/CocoModel' -utils = require 'lib/utils' +utils = require 'core/utils' class BlandClass extends CocoModel @className: 'Bland' @@ -93,7 +93,7 @@ describe 'CocoModel', -> b.patch() request = jasmine.Ajax.requests.mostRecent() attrs = JSON.stringify(b.attributes) # server responds with all - request.response({status: 200, responseText: attrs}) + request.respondWith({status: 200, responseText: attrs}) b.set('number', 3) b.patch() @@ -125,7 +125,7 @@ describe 'CocoModel', -> b = new BlandClass({}) res = b.save() request = jasmine.Ajax.requests.mostRecent() - request.response(status: 200, responseText: '{}') + request.respondWith(status: 200, responseText: '{}') collection = [] model = @@ -140,7 +140,7 @@ describe 'CocoModel', -> ready true else return ready false - request.response {status: 200, responseText: JSON.stringify collection} + request.respondWith {status: 200, responseText: JSON.stringify collection} utils.keepDoingUntil (ready) -> request = jasmine.Ajax.requests.mostRecent() @@ -149,7 +149,7 @@ describe 'CocoModel', -> ready true else return ready false - request.response {status:200, responseText: JSON.stringify me} + request.respondWith {status:200, responseText: JSON.stringify me} describe 'updateI18NCoverage', -> class FlexibleClass extends CocoModel diff --git a/test/app/models/SuperModel.spec.coffee b/test/app/models/SuperModel.spec.coffee index 12219a584..b900ff9c7 100644 --- a/test/app/models/SuperModel.spec.coffee +++ b/test/app/models/SuperModel.spec.coffee @@ -46,7 +46,7 @@ describe 'SuperModel', -> s.once 'loaded-all', -> triggered = true s.loadModel(m, 'user') request = jasmine.Ajax.requests.mostRecent() - request.response({status: 200, responseText: '{}'}) + request.respondWith({status: 200, responseText: '{}'}) _.defer -> expect(triggered).toBe(true) done() diff --git a/test/app/views/modal/AuthModal.spec.coffee b/test/app/views/core/AuthModal.spec.coffee similarity index 71% rename from test/app/views/modal/AuthModal.spec.coffee rename to test/app/views/core/AuthModal.spec.coffee index 199b265f4..698361dc6 100644 --- a/test/app/views/modal/AuthModal.spec.coffee +++ b/test/app/views/core/AuthModal.spec.coffee @@ -1,9 +1,9 @@ -AuthModal = require 'views/modal/AuthModal' -RecoverModal = require 'views/modal/RecoverModal' +AuthModal = require 'views/core/AuthModal' +RecoverModal = require 'views/core/RecoverModal' describe 'AuthModal', -> it 'opens the recover modal when you click the recover link', -> - m = new AuthModal() + m = new AuthModal({mode: 'login'}) m.render() spyOn(m, 'openModalView') m.$el.find('#link-to-recover').click() diff --git a/test/app/views/editor/component/ThangComponentsEditView.spec.coffee b/test/app/views/editor/component/ThangComponentsEditView.spec.coffee index a2349a8d9..49c31cdf7 100644 --- a/test/app/views/editor/component/ThangComponentsEditView.spec.coffee +++ b/test/app/views/editor/component/ThangComponentsEditView.spec.coffee @@ -34,7 +34,6 @@ describe 'ThangComponentsEditView', -> supermodel = new SuperModel() supermodel.registerModel(componentC) view = new ThangComponentEditView({ components: [], supermodel: supermodel }) - jasmine.Ajax.requests.sendResponses { '/db/thang.type': [] } _.defer -> view.render() view.componentsTreema.set('/', [ { original: 'C', majorVersion: 0 }]) diff --git a/test/app/views/editor/level/EditorLevelView.spec.coffee b/test/app/views/editor/level/EditorLevelView.spec.coffee index 7a9064993..35beea837 100644 --- a/test/app/views/editor/level/EditorLevelView.spec.coffee +++ b/test/app/views/editor/level/EditorLevelView.spec.coffee @@ -7,7 +7,7 @@ describe 'LevelEditView', -> it 'opens just one modal when you click it', -> view = new LevelEditView({}, 'something') request = jasmine.Ajax.requests.first() - request.response {status: 200, responseText: JSON.stringify(emptyLevel)} + request.respondWith {status: 200, responseText: JSON.stringify(emptyLevel)} view.render() spyOn(view, 'openModalView') view.$el.find('#revert-button').click() diff --git a/test/app/views/play/ladder/LadderTabView.coffee b/test/app/views/play/ladder/LadderTabView.coffee index e23fc26be..0fe946224 100644 --- a/test/app/views/play/ladder/LadderTabView.coffee +++ b/test/app/views/play/ladder/LadderTabView.coffee @@ -1,4 +1,4 @@ -LadderTabView = require 'views/play/ladder/LadderTabView' +LadderTabView = require 'views/ladder/LadderTabView' Level = require 'models/Level' fixtures = require 'test/app/fixtures/levels' @@ -14,5 +14,5 @@ describe 'LeaderboardData', -> request = jasmine.Ajax.requests.mostRecent() triggered = false leaderboard.once 'sync', -> triggered = true - request.response({status: 200, responseText: '{}'}) + request.respondWith({status: 200, responseText: '{}'}) expect(triggered).toBe(true) diff --git a/vendor/scripts/jasmine-boot.js b/vendor/scripts/jasmine-boot.js new file mode 100755 index 000000000..47b125211 --- /dev/null +++ b/vendor/scripts/jasmine-boot.js @@ -0,0 +1,176 @@ +/** + Starting with version 2.0, this file "boots" Jasmine, performing all of the necessary initialization before executing the loaded environment and all of a project's specs. This file should be loaded after `jasmine.js`, but before any project source files or spec files are loaded. Thus this file can also be used to customize Jasmine for a project. + + If a project is using Jasmine via the standalone distribution, this file can be customized directly. If a project is using Jasmine via the [Ruby gem][jasmine-gem], this file can be copied into the support directory via `jasmine copy_boot_js`. Other environments (e.g., Python) will have different mechanisms. + + The location of `boot.js` can be specified and/or overridden in `jasmine.yml`. + + [jasmine-gem]: http://github.com/pivotal/jasmine-gem + */ + +(function() { + + /** + * ## Require & Instantiate + * + * Require Jasmine's core files. Specifically, this requires and attaches all of Jasmine's code to the `jasmine` reference. + */ + window.jasmine = jasmineRequire.core(jasmineRequire); + + /** + * Since this is being run in a browser and the results should populate to an HTML page, require the HTML-specific Jasmine code, injecting the same reference. + */ + jasmineRequire.html(jasmine); + + /** + * Create the Jasmine environment. This is used to run all specs in a project. + */ + var env = jasmine.getEnv(); + + /** + * ## The Global Interface + * + * Build up the functions that will be exposed as the Jasmine public interface. A project can customize, rename or alias any of these functions as desired, provided the implementation remains unchanged. + */ + var jasmineInterface = { + describe: function(description, specDefinitions) { + return env.describe(description, specDefinitions); + }, + + xdescribe: function(description, specDefinitions) { + return env.xdescribe(description, specDefinitions); + }, + + it: function(desc, func) { + return env.it(desc, func); + }, + + xit: function(desc, func) { + return env.xit(desc, func); + }, + + beforeEach: function(beforeEachFunction) { + return env.beforeEach(beforeEachFunction); + }, + + afterEach: function(afterEachFunction) { + return env.afterEach(afterEachFunction); + }, + + expect: function(actual) { + return env.expect(actual); + }, + + pending: function() { + return env.pending(); + }, + + spyOn: function(obj, methodName) { + return env.spyOn(obj, methodName); + }, + + jsApiReporter: new jasmine.JsApiReporter({ + timer: new jasmine.Timer() + }) + }; + + /** + * Add all of the Jasmine global/public interface to the proper global, so a project can use the public interface directly. For example, calling `describe` in specs instead of `jasmine.getEnv().describe`. + */ + if (typeof window == "undefined" && typeof exports == "object") { + extend(exports, jasmineInterface); + } else { + extend(window, jasmineInterface); + } + + /** + * Expose the interface for adding custom equality testers. + */ + jasmine.addCustomEqualityTester = function(tester) { + env.addCustomEqualityTester(tester); + }; + + /** + * Expose the interface for adding custom expectation matchers + */ + jasmine.addMatchers = function(matchers) { + return env.addMatchers(matchers); + }; + + /** + * Expose the mock interface for the JavaScript timeout functions + */ + jasmine.clock = function() { + return env.clock; + }; + + /** + * ## Runner Parameters + * + * More browser specific code - wrap the query string in an object and to allow for getting/setting parameters from the runner user interface. + */ + + var queryString = new jasmine.QueryString({ + getWindowLocation: function() { return window.location; } + }); + + var catchingExceptions = false; // Setting to false always for CodeCombat, because Jasmine-HTML's reporter doesn't do source maps, and Chrome console does. + env.catchExceptions(typeof catchingExceptions === "undefined" ? true : catchingExceptions); + + /** + * ## Reporters + * The `HtmlReporter` builds all of the HTML UI for the runner page. This reporter paints the dots, stars, and x's for specs, as well as all spec names and all failures (if any). + */ + var htmlReporter = new jasmine.HtmlReporter({ + env: env, + onRaiseExceptionsClick: function() { queryString.setParam("catch", !env.catchingExceptions()); }, + getContainer: function() { return $('#testing-area')[0]; }, + createElement: function() { return document.createElement.apply(document, arguments); }, + createTextNode: function() { return document.createTextNode.apply(document, arguments); }, + timer: new jasmine.Timer() + }); + + /** + * The `jsApiReporter` also receives spec results, and is used by any environment that needs to extract the results from JavaScript. + */ + env.addReporter(jasmineInterface.jsApiReporter); + env.addReporter(htmlReporter); + + /** + * Filter which specs will be run by matching the start of the full name against the `spec` query param. + */ + var specFilter = new jasmine.HtmlSpecFilter({ + filterString: function() { return queryString.getParam("spec"); } + }); + + env.specFilter = function(spec) { + return specFilter.matches(spec.getFullName()); + }; + + /** + * Setting up timing functions to be able to be overridden. Certain browsers (Safari, IE 8, phantomjs) require this hack. + */ + window.setTimeout = window.setTimeout; + window.setInterval = window.setInterval; + window.clearTimeout = window.clearTimeout; + window.clearInterval = window.clearInterval; + + /** + * ## Execution + * + * Replace the browser window's `onload`, ensure it's called, and then run all of the loaded specs. This includes initializing the `HtmlReporter` instance and then executing the loaded Jasmine environment. All of this will happen after all of the specs are loaded. + */ + window.runJasmine = function() { + htmlReporter.initialize(); + env.execute(); + }; + + /** + * Helper function for readability above. + */ + function extend(destination, source) { + for (var property in source) destination[property] = source[property]; + return destination; + } + +}()); diff --git a/app/assets/javascripts/jasmine-html.js b/vendor/scripts/jasmine-html.js similarity index 100% rename from app/assets/javascripts/jasmine-html.js rename to vendor/scripts/jasmine-html.js diff --git a/vendor/scripts/jasmine-mock-ajax.js b/vendor/scripts/jasmine-mock-ajax.js new file mode 100644 index 000000000..232844393 --- /dev/null +++ b/vendor/scripts/jasmine-mock-ajax.js @@ -0,0 +1,609 @@ +/* + +Jasmine-Ajax : a set of helpers for testing AJAX requests under the Jasmine +BDD framework for JavaScript. + +http://github.com/pivotal/jasmine-ajax + +Jasmine Home page: http://pivotal.github.com/jasmine + +Copyright (c) 2008-2013 Pivotal Labs + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND +NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE +LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION +WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. + +*/ + +getJasmineRequireObj().ajax = function(jRequire) { + var $ajax = {}; + + $ajax.RequestStub = jRequire.AjaxRequestStub(); + $ajax.RequestTracker = jRequire.AjaxRequestTracker(); + $ajax.StubTracker = jRequire.AjaxStubTracker(); + $ajax.ParamParser = jRequire.AjaxParamParser(); + $ajax.fakeRequest = jRequire.AjaxFakeRequest(); + $ajax.MockAjax = jRequire.MockAjax($ajax); + + return $ajax.MockAjax; +}; + +getJasmineRequireObj().AjaxFakeRequest = function() { + function extend(destination, source, propertiesToSkip) { + propertiesToSkip = propertiesToSkip || []; + for (var property in source) { + if (!arrayContains(propertiesToSkip, property)) { + destination[property] = source[property]; + } + } + return destination; + } + + function arrayContains(arr, item) { + for (var i = 0; i < arr.length; i++) { + if (arr[i] === item) { + return true; + } + } + return false; + } + + function wrapProgressEvent(xhr, eventName) { + return function() { + if (xhr[eventName]) { + xhr[eventName](); + } + }; + } + + function initializeEvents(xhr) { + return { + 'loadstart': wrapProgressEvent(xhr, 'onloadstart'), + 'load': wrapProgressEvent(xhr, 'onload'), + 'loadend': wrapProgressEvent(xhr, 'onloadend'), + 'progress': wrapProgressEvent(xhr, 'onprogress'), + 'error': wrapProgressEvent(xhr, 'onerror'), + 'abort': wrapProgressEvent(xhr, 'onabort'), + 'timeout': wrapProgressEvent(xhr, 'ontimeout') + }; + } + + function unconvertibleResponseTypeMessage(type) { + var msg = [ + "Can't build XHR.response for XHR.responseType of '", + type, + "'.", + "XHR.response must be explicitly stubbed" + ]; + return msg.join(' '); + } + + function fakeRequest(global, requestTracker, stubTracker, paramParser) { + function FakeXMLHttpRequest() { + requestTracker.track(this); + this.events = initializeEvents(this); + this.requestHeaders = {}; + this.overriddenMimeType = null; + } + + function findHeader(name, headers) { + name = name.toLowerCase(); + for (var header in headers) { + if (header.toLowerCase() === name) { + return headers[header]; + } + } + } + + function normalizeHeaders(rawHeaders, contentType) { + var headers = []; + + if (rawHeaders) { + if (rawHeaders instanceof Array) { + headers = rawHeaders; + } else { + for (var headerName in rawHeaders) { + if (rawHeaders.hasOwnProperty(headerName)) { + headers.push({ name: headerName, value: rawHeaders[headerName] }); + } + } + } + } else { + headers.push({ name: "Content-Type", value: contentType || "application/json" }); + } + + return headers; + } + + function parseXml(xmlText, contentType) { + if (global.DOMParser) { + return (new global.DOMParser()).parseFromString(xmlText, 'text/xml'); + } else { + var xml = new global.ActiveXObject("Microsoft.XMLDOM"); + xml.async = "false"; + xml.loadXML(xmlText); + return xml; + } + } + + var xmlParsables = ['text/xml', 'application/xml']; + + function getResponseXml(responseText, contentType) { + if (arrayContains(xmlParsables, contentType.toLowerCase())) { + return parseXml(responseText, contentType); + } else if (contentType.match(/\+xml$/)) { + return parseXml(responseText, 'text/xml'); + } + return null; + } + + var iePropertiesThatCannotBeCopied = ['responseBody', 'responseText', 'responseXML', 'status', 'statusText', 'responseTimeout']; + extend(FakeXMLHttpRequest.prototype, new global.XMLHttpRequest(), iePropertiesThatCannotBeCopied); + extend(FakeXMLHttpRequest.prototype, { + open: function() { + this.method = arguments[0]; + this.url = arguments[1]; + this.username = arguments[3]; + this.password = arguments[4]; + this.readyState = 1; + this.onreadystatechange(); + }, + + setRequestHeader: function(header, value) { + if(this.requestHeaders.hasOwnProperty(header)) { + this.requestHeaders[header] = [this.requestHeaders[header], value].join(', '); + } else { + this.requestHeaders[header] = value; + } + }, + + overrideMimeType: function(mime) { + this.overriddenMimeType = mime; + }, + + abort: function() { + this.readyState = 0; + this.status = 0; + this.statusText = "abort"; + this.onreadystatechange(); + this.events.progress(); + this.events.abort(); + this.events.loadend(); + }, + + readyState: 0, + + onloadstart: null, + onprogress: null, + onabort: null, + onerror: null, + onload: null, + ontimeout: null, + onloadend: null, + + onreadystatechange: function(isTimeout) { + }, + + addEventListener: function(event, callback) { + var existingCallback = this.events[event], + self = this; + + this.events[event] = function() { + callback.apply(self); + existingCallback(); + }; + }, + + status: null, + + send: function(data) { + this.params = data; + this.readyState = 2; + this.events.loadstart(); + this.onreadystatechange(); + + var stub = stubTracker.findStub(this.url, data, this.method); + if (stub) { + this.respondWith(stub); + } + }, + + contentType: function() { + return findHeader('content-type', this.requestHeaders); + }, + + data: function() { + if (!this.params) { + return {}; + } + + return paramParser.findParser(this).parse(this.params); + }, + + getResponseHeader: function(name) { + name = name.toLowerCase(); + var resultHeader; + for(var i = 0; i < this.responseHeaders.length; i++) { + var header = this.responseHeaders[i]; + if (name === header.name.toLowerCase()) { + if (resultHeader) { + resultHeader = [resultHeader, header.value].join(', '); + } else { + resultHeader = header.value; + } + } + } + return resultHeader; + }, + + getAllResponseHeaders: function() { + var responseHeaders = []; + for (var i = 0; i < this.responseHeaders.length; i++) { + responseHeaders.push(this.responseHeaders[i].name + ': ' + + this.responseHeaders[i].value); + } + return responseHeaders.join('\r\n'); + }, + + responseText: null, + response: null, + responseType: null, + + responseValue: function() { + switch(this.responseType) { + case null: + case "": + case "text": + return this.readyState >= 3 ? this.responseText : ""; + case "json": + return JSON.parse(this.responseText); + case "arraybuffer": + throw unconvertibleResponseTypeMessage('arraybuffer'); + case "blob": + throw unconvertibleResponseTypeMessage('blob'); + case "document": + return this.responseXML; + } + }, + + + respondWith: function(response) { + if (this.readyState === 4) { + throw new Error("FakeXMLHttpRequest already completed"); + } + this.status = response.status; + this.statusText = response.statusText || ""; + this.responseText = response.responseText || ""; + this.responseType = response.responseType || ""; + this.readyState = 4; + this.responseHeaders = normalizeHeaders(response.responseHeaders, response.contentType); + this.responseXML = getResponseXml(response.responseText, this.getResponseHeader('content-type') || ''); + if (this.responseXML) { + this.responseType = 'document'; + } + + if ('response' in response) { + this.response = response.response; + } else { + this.response = this.responseValue(); + } + + this.onreadystatechange(); + this.events.progress(); + this.events.load(); + this.events.loadend(); + }, + + responseTimeout: function() { + if (this.readyState === 4) { + throw new Error("FakeXMLHttpRequest already completed"); + } + this.readyState = 4; + jasmine.clock().tick(30000); + this.onreadystatechange('timeout'); + this.events.progress(); + this.events.timeout(); + this.events.loadend(); + }, + + responseError: function() { + if (this.readyState === 4) { + throw new Error("FakeXMLHttpRequest already completed"); + } + this.readyState = 4; + this.onreadystatechange(); + this.events.progress(); + this.events.error(); + this.events.loadend(); + } + }); + + return FakeXMLHttpRequest; + } + + return fakeRequest; +}; + +getJasmineRequireObj().MockAjax = function($ajax) { + function MockAjax(global) { + var requestTracker = new $ajax.RequestTracker(), + stubTracker = new $ajax.StubTracker(), + paramParser = new $ajax.ParamParser(), + realAjaxFunction = global.XMLHttpRequest, + mockAjaxFunction = $ajax.fakeRequest(global, requestTracker, stubTracker, paramParser); + + this.install = function() { + global.XMLHttpRequest = mockAjaxFunction; + }; + + this.uninstall = function() { + global.XMLHttpRequest = realAjaxFunction; + + this.stubs.reset(); + this.requests.reset(); + paramParser.reset(); + }; + + this.stubRequest = function(url, data, method) { + var stub = new $ajax.RequestStub(url, data, method); + stubTracker.addStub(stub); + return stub; + }; + + this.withMock = function(closure) { + this.install(); + try { + closure(); + } finally { + this.uninstall(); + } + }; + + this.addCustomParamParser = function(parser) { + paramParser.add(parser); + }; + + this.requests = requestTracker; + this.stubs = stubTracker; + } + + return MockAjax; +}; + +getJasmineRequireObj().AjaxParamParser = function() { + function ParamParser() { + var defaults = [ + { + test: function(xhr) { + return (/^application\/json/).test(xhr.contentType()); + }, + parse: function jsonParser(paramString) { + return JSON.parse(paramString); + } + }, + { + test: function(xhr) { + return true; + }, + parse: function naiveParser(paramString) { + var data = {}; + var params = paramString.split('&'); + + for (var i = 0; i < params.length; ++i) { + var kv = params[i].replace(/\+/g, ' ').split('='); + var key = decodeURIComponent(kv[0]); + data[key] = data[key] || []; + data[key].push(decodeURIComponent(kv[1])); + } + return data; + } + } + ]; + var paramParsers = []; + + this.add = function(parser) { + paramParsers.unshift(parser); + }; + + this.findParser = function(xhr) { + for(var i in paramParsers) { + var parser = paramParsers[i]; + if (parser.test(xhr)) { + return parser; + } + } + }; + + this.reset = function() { + paramParsers = []; + for(var i in defaults) { + paramParsers.push(defaults[i]); + } + }; + + this.reset(); + } + + return ParamParser; +}; + +getJasmineRequireObj().AjaxRequestStub = function() { + function RequestStub(url, stubData, method) { + var normalizeQuery = function(query) { + return query ? query.split('&').sort().join('&') : undefined; + }; + + if (url instanceof RegExp) { + this.url = url; + this.query = undefined; + } else { + var split = url.split('?'); + this.url = split[0]; + this.query = split.length > 1 ? normalizeQuery(split[1]) : undefined; + } + + this.data = normalizeQuery(stubData); + this.method = method; + + this.andReturn = function(options) { + this.status = options.status || 200; + + this.contentType = options.contentType; + this.response = options.response; + this.responseText = options.responseText; + }; + + this.matches = function(fullUrl, data, method) { + var matches = false; + fullUrl = fullUrl.toString(); + if (this.url instanceof RegExp) { + matches = this.url.test(fullUrl); + } else { + var urlSplit = fullUrl.split('?'), + url = urlSplit[0], + query = urlSplit[1]; + matches = this.url === url && this.query === normalizeQuery(query); + } + return matches && (!this.data || this.data === normalizeQuery(data)) && (!this.method || this.method === method); + }; + } + + return RequestStub; +}; + +getJasmineRequireObj().AjaxRequestTracker = function() { + function RequestTracker() { + var requests = []; + + this.track = function(request) { + requests.push(request); + }; + + this.first = function() { + return requests[0]; + }; + + this.count = function() { + return requests.length; + }; + + this.reset = function() { + requests = []; + }; + + this.mostRecent = function() { + return requests[requests.length - 1]; + }; + + this.at = function(index) { + return requests[index]; + }; + + this.all = function() { + return requests.slice(0); + }; + + this.sendResponses = function(responseMap) { + var urls = Object.keys(responseMap); + var success = true; + for(var i in urls) { + var url = urls[i]; + var responseBody = responseMap[url]; + var responded = false; + + var requests = jasmine.Ajax.requests.all().slice(); + for(var j in requests) { + var request = requests[j]; + if(request.url.startsWith(url)) { + request.respondWith({status: 200, responseText: JSON.stringify(responseBody)}); + responded = true; + break; + } + } + if(!responded) { + var allRequests = jasmine.Ajax.requests.all(); + urls = []; + for(var k in allRequests) urls.push(allRequests[k].url); + console.error('could not find response for', url, 'in', urls, allRequests); + success = false; + continue; + } + } + return success; + } + + this.filter = function(url_to_match) { + var matching_requests = []; + + for (var i = 0; i < requests.length; i++) { + if (url_to_match instanceof RegExp && + url_to_match.test(requests[i].url)) { + matching_requests.push(requests[i]); + } else if (url_to_match instanceof Function && + url_to_match(requests[i])) { + matching_requests.push(requests[i]); + } else { + if (requests[i].url === url_to_match) { + matching_requests.push(requests[i]); + } + } + } + + return matching_requests; + }; + } + + return RequestTracker; +}; + +getJasmineRequireObj().AjaxStubTracker = function() { + function StubTracker() { + var stubs = []; + + this.addStub = function(stub) { + stubs.push(stub); + }; + + this.reset = function() { + stubs = []; + }; + + this.findStub = function(url, data, method) { + for (var i = stubs.length - 1; i >= 0; i--) { + var stub = stubs[i]; + if (stub.matches(url, data, method)) { + return stub; + } + } + }; + } + + return StubTracker; +}; + +(function() { + var jRequire = getJasmineRequireObj(), + MockAjax = jRequire.ajax(jRequire); + if (typeof window === "undefined" && typeof exports === "object") { + exports.MockAjax = MockAjax; + jasmine.Ajax = new MockAjax(exports); + } else { + window.MockAjax = MockAjax; + jasmine.Ajax = new MockAjax(window); + } +}()); diff --git a/app/assets/javascripts/jasmine.js b/vendor/scripts/jasmine.js similarity index 100% rename from app/assets/javascripts/jasmine.js rename to vendor/scripts/jasmine.js