Merge pull request #12204 from edx/fedx/krma-conf-tnl4102

Use Karma as test runner with Jasmine 2.4.
This commit is contained in:
Usman Khalid
2016-04-22 20:28:01 +05:00
229 changed files with 5817 additions and 3970 deletions

View File

@@ -1,4 +1,5 @@
requirejs.config({
baseUrl: '/base/',
paths: {
"gettext": "xmodule_js/common_static/js/test/i18n",
"mustache": "xmodule_js/common_static/js/vendor/mustache",
@@ -42,10 +43,9 @@ requirejs.config({
"accessibility": "xmodule_js/common_static/js/src/accessibility_tools",
"sinon": "xmodule_js/common_static/js/vendor/sinon-1.17.0",
"squire": "xmodule_js/common_static/js/vendor/Squire",
"jasmine-jquery": "xmodule_js/common_static/js/vendor/jasmine-jquery",
"jasmine-imagediff": "xmodule_js/common_static/js/vendor/jasmine-imagediff",
"jasmine-stealth": "xmodule_js/common_static/js/vendor/jasmine-stealth",
"jasmine.async": "xmodule_js/common_static/js/vendor/jasmine.async",
"jasmine-stealth": "xmodule_js/common_static/js/libs/jasmine-stealth",
"jasmine-waituntil": "xmodule_js/common_static/js/libs/jasmine-waituntil",
"draggabilly": "xmodule_js/common_static/js/vendor/draggabilly",
"domReady": "xmodule_js/common_static/js/vendor/domReady",
"URI": "xmodule_js/common_static/js/vendor/URI.min",
@@ -158,17 +158,17 @@ requirejs.config({
"mathjax": {
exports: "MathJax",
init: ->
MathJax.Hub.Config
tex2jax:
inlineMath: [
["\\(","\\)"],
['[mathjaxinline]','[/mathjaxinline]']
]
displayMath: [
["\\[","\\]"],
['[mathjax]','[/mathjax]']
]
MathJax.Hub.Configured()
MathJax.Hub.Config
tex2jax:
inlineMath: [
["\\(", "\\)"],
['[mathjaxinline]', '[/mathjaxinline]']
]
displayMath: [
["\\[", "\\]"],
['[mathjax]', '[/mathjax]']
]
MathJax.Hub.Configured()
},
"URI": {
exports: "URI"
@@ -179,18 +179,12 @@ requirejs.config({
"sinon": {
exports: "sinon"
},
"jasmine-jquery": {
deps: ["jasmine"]
},
"jasmine-imagediff": {
deps: ["jasmine"]
},
"jasmine-imagediff": {},
"jasmine-stealth": {
deps: ["jasmine"]
deps: ["underscore", "underscore.string"]
},
"jasmine.async": {
deps: ["jasmine"],
exports: "AsyncSpec"
"jasmine-waituntil": {
deps: ["jquery"]
},
"xblock/core": {
exports: "XBlock",
@@ -201,7 +195,7 @@ requirejs.config({
deps: ["xblock/core"]
},
"mock-ajax": {
deps: ["jasmine", "jquery"]
deps: ["jquery"]
}
"coffee/src/main": {
@@ -221,35 +215,33 @@ requirejs.config({
jasmine.getFixtures().fixturesPath += 'coffee/fixtures'
define([
testFiles = [
"coffee/spec/main_spec",
"coffee/spec/models/course_spec", "coffee/spec/models/metadata_spec",
"coffee/spec/models/course_spec",
"coffee/spec/models/metadata_spec",
"coffee/spec/models/section_spec",
"coffee/spec/models/settings_course_grader_spec",
"coffee/spec/models/settings_grading_spec", "coffee/spec/models/textbook_spec",
"coffee/spec/models/settings_grading_spec",
"coffee/spec/models/textbook_spec",
"coffee/spec/models/upload_spec",
"coffee/spec/views/course_info_spec",
"coffee/spec/views/metadata_edit_spec",
"coffee/spec/views/module_edit_spec",
"coffee/spec/views/textbook_spec",
"coffee/spec/views/upload_spec",
"js/spec/video/transcripts/utils_spec", "js/spec/video/transcripts/editor_spec",
"js/spec/video/transcripts/videolist_spec", "js/spec/video/transcripts/message_manager_spec",
"js/spec/video/transcripts/file_uploader_spec",
"js/spec/video/transcripts/utils_spec",
"js/spec/video/transcripts/editor_spec",
# "js/spec/video/transcripts/videolist_spec",
# "js/spec/video/transcripts/message_manager_spec",
# "js/spec/video/transcripts/file_uploader_spec",
"js/spec/models/component_template_spec",
"js/spec/models/explicit_url_spec",
"js/spec/models/xblock_info_spec",
"js/spec/models/xblock_validation_spec",
"js/spec/models/license_spec",
"js/spec/utils/drag_and_drop_spec",
"js/spec/utils/handle_iframe_binding_spec",
"js/spec/utils/module_spec",
"js/spec/views/active_video_upload_list_spec",
"js/spec/views/previous_video_upload_spec",
"js/spec/views/previous_video_upload_list_spec",
@@ -266,7 +258,6 @@ define([
"js/spec/views/license_spec",
"js/spec/views/paging_spec",
"js/spec/views/login_studio_spec",
"js/spec/views/pages/container_spec",
"js/spec/views/pages/container_subviews_spec",
"js/spec/views/pages/group_configurations_spec",
@@ -274,25 +265,24 @@ define([
"js/spec/views/pages/course_rerun_spec",
"js/spec/views/pages/index_spec",
"js/spec/views/pages/library_users_spec",
"js/spec/views/modals/base_modal_spec",
"js/spec/views/modals/edit_xblock_spec",
"js/spec/views/modals/validation_error_modal_spec",
"js/spec/views/settings/main_spec",
"js/spec/factories/xblock_validation_spec",
"js/spec/xblock/cms.runtime.v1_spec",
# Certificates application test suite mappings
"js/certificates/spec/models/certificate_spec",
"js/certificates/spec/views/certificate_details_spec",
"js/certificates/spec/views/certificate_editor_spec",
"js/certificates/spec/views/certificates_list_spec",
"js/certificates/spec/views/certificate_preview_spec",
"js/certificates/spec/views/certificate_preview_spec"
]
# these tests are run separately in the cms-squire suite, due to process
# isolation issues with Squire.js
# "coffee/spec/views/assets_spec"
])
i = 0
while i < testFiles.length
testFiles[i] = '/base/' + testFiles[i] + '.js'
i++
require testFiles, ->
# start test run, once Require.js is done
window.__karma__.start()

View File

@@ -1,4 +1,5 @@
require ["jquery", "backbone", "coffee/src/main", "common/js/spec_helpers/ajax_helpers", "jasmine-stealth", "jquery.cookie"],
require ["jquery", "backbone", "coffee/src/main", "common/js/spec_helpers/ajax_helpers",
"jasmine-stealth", "jasmine-waituntil", "jquery.cookie"],
($, Backbone, main, AjaxHelpers) ->
describe "CMS", ->
it "should initialize URL", ->
@@ -7,8 +8,12 @@ require ["jquery", "backbone", "coffee/src/main", "common/js/spec_helpers/ajax_h
describe "main helper", ->
beforeEach ->
@previousAjaxSettings = $.extend(true, {}, $.ajaxSettings)
spyOn($, "cookie")
$.cookie.when("csrftoken").thenReturn("stubCSRFToken")
spyOn($, "cookie").and.callFake(
(param) ->
if param == "csrftoken"
return "stubCSRFToken"
)
main()
afterEach ->
@@ -21,12 +26,15 @@ require ["jquery", "backbone", "coffee/src/main", "common/js/spec_helpers/ajax_h
expect($.ajaxSettings.headers["X-CSRFToken"]).toEqual("stubCSRFToken")
describe "AJAX Errors", ->
server = null
beforeEach ->
appendSetFixtures(sandbox({id: "page-notification"}))
afterEach ->
server && server.restore()
it "successful AJAX request does not pop an error notification", ->
server = AjaxHelpers.server(this, [200, {}, ''])
server = AjaxHelpers.server([200, {}, ''])
expect($("#page-notification")).toBeEmpty()
$.ajax("/test")
@@ -35,15 +43,15 @@ require ["jquery", "backbone", "coffee/src/main", "common/js/spec_helpers/ajax_h
expect($("#page-notification")).toBeEmpty()
it "AJAX request with error should pop an error notification", ->
server = AjaxHelpers.server(this, [500, {}, ''])
server = AjaxHelpers.server([500, {}, ''])
$.ajax("/test")
server.respond()
expect($("#page-notification")).not.toBeEmpty()
expect($("#page-notification")).toContain('div.wrapper-notification-error')
expect($("#page-notification")).toContainElement('div.wrapper-notification-error')
it "can override AJAX request with error so it does not pop an error notification", ->
server = AjaxHelpers.server(this, [500, {}, ''])
server = AjaxHelpers.server([500, {}, ''])
$.ajax
url: "/test"

View File

@@ -1,4 +1,6 @@
requirejs.config({
baseUrl: '/base/',
paths: {
"gettext": "xmodule_js/common_static/js/test/i18n",
"mustache": "xmodule_js/common_static/js/vendor/mustache",
@@ -22,8 +24,8 @@ requirejs.config({
"datepair": "xmodule_js/common_static/js/vendor/timepicker/datepair",
"date": "xmodule_js/common_static/js/vendor/date",
"text": "xmodule_js/common_static/js/vendor/requirejs/text",
"underscore": "xmodule_js/common_static/common/js/vendor/underscore",
"underscore.string": "xmodule_js/common_static/common/js/vendor/underscore.string",
"underscore": "common/js/vendor/underscore",
"underscore.string": "common/js/vendor/underscore.string",
"backbone": "xmodule_js/common_static/js/vendor/backbone-min",
"backbone.associations": "xmodule_js/common_static/js/vendor/backbone-associations-min",
"backbone.paginator": "xmodule_js/common_static/js/vendor/backbone.paginator.min",
@@ -36,11 +38,11 @@ requirejs.config({
"utility": "xmodule_js/common_static/js/src/utility",
"sinon": "xmodule_js/common_static/js/vendor/sinon-1.17.0",
"squire": "xmodule_js/common_static/js/vendor/Squire",
"jasmine-stealth": "xmodule_js/common_static/js/vendor/jasmine-stealth",
"jasmine.async": "xmodule_js/common_static/js/vendor/jasmine.async",
"modernizr": "xmodule_js/common_static/edx-pattern-library/js/modernizr-custom",
"afontgarde": "xmodule_js/common_static/edx-pattern-library/js/afontgarde",
"edxicons": "xmodule_js/common_static/edx-pattern-library/js/edx-icons",
"jasmine-stealth": "xmodule_js/common_static/js/libs/jasmine-stealth",
"jasmine-waituntil": "xmodule_js/common_static/js/libs/jasmine-waituntil",
"draggabilly": "xmodule_js/common_static/js/vendor/draggabilly",
"domReady": "xmodule_js/common_static/js/vendor/domReady",
"URI": "xmodule_js/common_static/js/vendor/URI.min",
@@ -159,11 +161,10 @@ requirejs.config({
exports: "sinon"
},
"jasmine-stealth": {
deps: ["jasmine"]
deps: ["underscore", "underscore.string"]
},
"jasmine.async": {
deps: ["jasmine"],
exports: "AsyncSpec"
"jasmine-waituntil": {
deps: ["jquery"]
},
"xblock/core": {
exports: "XBlock",
@@ -191,9 +192,16 @@ requirejs.config({
jasmine.getFixtures().fixturesPath += 'coffee/fixtures'
define([
"coffee/spec/views/assets_spec",
"js/spec/video/translations_editor_spec",
"js/spec/video/file_uploader_editor_spec",
"js/spec/models/group_configuration_spec"
])
testFiles = [
'coffee/spec/views/assets_spec',
'js/spec/video/translations_editor_spec',
'js/spec/video/file_uploader_editor_spec',
'js/spec/models/group_configuration_spec'
]
i = 0
while i < testFiles.length
testFiles[i] = '/base/' + testFiles[i] + '.js'
i++
require testFiles, ->
# start test run, once Require.js is done
window.__karma__.start()

View File

@@ -34,7 +34,7 @@ define ["js/models/section", "common/js/spec_helpers/ajax_helpers", "js/utils/mo
})
it "show/hide a notification when it saves to the server", ->
server = AjaxHelpers.server(this, [200, {}, ''])
server = AjaxHelpers.server([200, {}, ''])
@model.save()
expect(Section.prototype.showNotification).toHaveBeenCalled()
@@ -43,7 +43,7 @@ define ["js/models/section", "common/js/spec_helpers/ajax_helpers", "js/utils/mo
it "don't hide notification when saving fails", ->
# this is handled by the global AJAX error handler
server = AjaxHelpers.server(this, [500, {}, ''])
server = AjaxHelpers.server([500, {}, ''])
@model.save()
server.respond()

View File

@@ -1,12 +1,6 @@
define ["backbone", "js/models/textbook", "js/collections/textbook", "js/models/chapter", "js/collections/chapter", "coffee/src/main"],
(Backbone, Textbook, TextbookSet, Chapter, ChapterSet, main) ->
beforeEach ->
@addMatchers
toBeInstanceOf: (expected) ->
return @actual instanceof expected
describe "Textbook model", ->
beforeEach ->
main()

View File

@@ -1,25 +1,25 @@
define ["jquery", "jasmine", "common/js/spec_helpers/ajax_helpers", "squire"],
($, jasmine, AjaxHelpers, Squire) ->
define ["jquery", "common/js/spec_helpers/ajax_helpers", "squire"],
($, AjaxHelpers, Squire) ->
assetLibraryTpl = readFixtures('asset-library.underscore')
assetTpl = readFixtures('asset.underscore')
describe "Asset view", ->
beforeEach ->
beforeEach (done) ->
setFixtures($("<script>", {id: "asset-tpl", type: "text/template"}).text(assetTpl))
appendSetFixtures(sandbox({id: "page-prompt"}))
@promptSpies = jasmine.createSpyObj('Prompt.Warning', ["constructor", "show", "hide"])
@promptSpies.constructor.andReturn(@promptSpies)
@promptSpies.show.andReturn(@promptSpies)
@promptSpies.constructor.and.returnValue(@promptSpies)
@promptSpies.show.and.returnValue(@promptSpies)
@confirmationSpies = jasmine.createSpyObj('Notification.Confirmation', ["constructor", "show"])
@confirmationSpies.constructor.andReturn(@confirmationSpies)
@confirmationSpies.show.andReturn(@confirmationSpies)
@confirmationSpies.constructor.and.returnValue(@confirmationSpies)
@confirmationSpies.show.and.returnValue(@confirmationSpies)
@savingSpies = jasmine.createSpyObj('Notification.Mini', ["constructor", "show", "hide"])
@savingSpies.constructor.andReturn(@savingSpies)
@savingSpies.show.andReturn(@savingSpies)
@savingSpies.constructor.and.returnValue(@savingSpies)
@savingSpies.show.and.returnValue(@savingSpies)
@injector = new Squire()
@injector.mock("common/js/components/views/feedback_prompt", {
@@ -29,8 +29,8 @@ define ["jquery", "jasmine", "common/js/spec_helpers/ajax_helpers", "squire"],
"Confirmation": @confirmationSpies.constructor,
"Mini": @savingSpies.constructor
})
runs =>
@injector.require ["js/models/asset", "js/collections/asset", "js/views/asset"],
@injector.require ["js/models/asset", "js/collections/asset", "js/views/asset"],
(AssetModel, AssetCollection, AssetView) =>
@model = new AssetModel
display_name: "test asset"
@@ -39,8 +39,8 @@ define ["jquery", "jasmine", "common/js/spec_helpers/ajax_helpers", "squire"],
date_added: 'date'
thumbnail: null
id: 'id'
spyOn(@model, "destroy").andCallThrough()
spyOn(@model, "save").andCallThrough()
spyOn(@model, "destroy").and.callThrough()
spyOn(@model, "save").and.callThrough()
@collection = new AssetCollection([@model])
@collection.url = "assets-url"
@@ -48,8 +48,7 @@ define ["jquery", "jasmine", "common/js/spec_helpers/ajax_helpers", "squire"],
view = new AssetView({model: @model})
requests = if test then AjaxHelpers["requests"](test) else null
return {view: view, requests: requests}
waitsFor (=> @createAssetView), "AssetsView Creation function was not initialized", 1000
done()
afterEach ->
@injector.clean()
@@ -65,7 +64,7 @@ define ["jquery", "jasmine", "common/js/spec_helpers/ajax_helpers", "squire"],
{view: @view, requests: requests} = @createAssetView()
@view.render().$(".remove-asset-button").click()
expect(@promptSpies.constructor).toHaveBeenCalled()
ctorOptions = @promptSpies.constructor.mostRecentCall.args[0]
ctorOptions = @promptSpies.constructor.calls.mostRecent().args[0]
expect(ctorOptions.title).toMatch('Delete File Confirmation')
# hasn't actually been removed
expect(@model.destroy).not.toHaveBeenCalled()
@@ -76,7 +75,7 @@ define ["jquery", "jasmine", "common/js/spec_helpers/ajax_helpers", "squire"],
{view: @view, requests: requests} = @createAssetView(this)
@view.render().$(".remove-asset-button").click()
ctorOptions = @promptSpies.constructor.mostRecentCall.args[0]
ctorOptions = @promptSpies.constructor.calls.mostRecent().args[0]
# run the primary function to indicate confirmation
ctorOptions.actions.primary.click(@promptSpies)
# AJAX request has been sent, but not yet returned
@@ -88,7 +87,7 @@ define ["jquery", "jasmine", "common/js/spec_helpers/ajax_helpers", "squire"],
requests[0].respond(200)
expect(@confirmationSpies.constructor).toHaveBeenCalled()
expect(@confirmationSpies.show).toHaveBeenCalled()
savingOptions = @confirmationSpies.constructor.mostRecentCall.args[0]
savingOptions = @confirmationSpies.constructor.calls.mostRecent().args[0]
expect(savingOptions.title).toMatch("Your file has been deleted.")
expect(@collection.contains(@model)).toBeFalsy()
@@ -96,7 +95,7 @@ define ["jquery", "jasmine", "common/js/spec_helpers/ajax_helpers", "squire"],
{view: @view, requests: requests} = @createAssetView(this)
@view.render().$(".remove-asset-button").click()
ctorOptions = @promptSpies.constructor.mostRecentCall.args[0]
ctorOptions = @promptSpies.constructor.calls.mostRecent().args[0]
# run the primary function to indicate confirmation
ctorOptions.actions.primary.click(@promptSpies)
# AJAX request has been sent, but not yet returned
@@ -115,7 +114,7 @@ define ["jquery", "jasmine", "common/js/spec_helpers/ajax_helpers", "squire"],
expect(requests.length).toEqual(1)
expect(@savingSpies.constructor).toHaveBeenCalled()
expect(@savingSpies.show).toHaveBeenCalled()
savingOptions = @savingSpies.constructor.mostRecentCall.args[0]
savingOptions = @savingSpies.constructor.calls.mostRecent().args[0]
expect(savingOptions.title).toMatch("Saving")
expect(@model.get("locked")).toBeFalsy()
# return a success response
@@ -134,7 +133,7 @@ define ["jquery", "jasmine", "common/js/spec_helpers/ajax_helpers", "squire"],
expect(@model.get("locked")).toBeFalsy()
describe "Assets view", ->
beforeEach ->
beforeEach (done) ->
setFixtures($("<script>", {id: "asset-library-tpl", type: "text/template"}).text(assetLibraryTpl))
appendSetFixtures($("<script>", {id: "asset-tpl", type: "text/template"}).text(assetTpl))
window.analytics = jasmine.createSpyObj('analytics', ['track'])
@@ -142,8 +141,8 @@ define ["jquery", "jasmine", "common/js/spec_helpers/ajax_helpers", "squire"],
appendSetFixtures(sandbox({id: "asset_table_body"}))
@promptSpies = jasmine.createSpyObj('Prompt.Warning', ["constructor", "show", "hide"])
@promptSpies.constructor.andReturn(@promptSpies)
@promptSpies.show.andReturn(@promptSpies)
@promptSpies.constructor.and.returnValue(@promptSpies)
@promptSpies.show.and.returnValue(@promptSpies)
@injector = new Squire()
@injector.mock("common/js/components/views/feedback_prompt", {
@@ -175,8 +174,7 @@ define ["jquery", "jasmine", "common/js/spec_helpers/ajax_helpers", "squire"],
totalCount: 2
}
runs =>
@injector.require ["js/models/asset", "js/collections/asset", "js/views/assets"],
@injector.require ["js/models/asset", "js/collections/asset", "js/views/assets"],
(AssetModel, AssetCollection, AssetsView) =>
@AssetModel = AssetModel
@collection = new AssetCollection();
@@ -188,9 +186,7 @@ define ["jquery", "jasmine", "common/js/spec_helpers/ajax_helpers", "squire"],
el: $('#asset_table_body')
view.render()
return {view: view, requests: requests}
waitsFor (=> @createAssetsView), "AssetsView Creation function was not initialized", 2000
done()
$.ajax()
@@ -294,7 +290,7 @@ define ["jquery", "jasmine", "common/js/spec_helpers/ajax_helpers", "squire"],
setup.call(this, requests)
# Delete the 2nd asset with success from server.
@view.$(".remove-asset-button")[1].click()
@promptSpies.constructor.mostRecentCall.args[0].actions.primary.click(@promptSpies)
@promptSpies.constructor.calls.mostRecent().args[0].actions.primary.click(@promptSpies)
AjaxHelpers.respondWithNoContent(requests)
expect(@view.$el).toContainText("test asset 1")
expect(@view.$el).not.toContainText("test asset 2")
@@ -304,7 +300,7 @@ define ["jquery", "jasmine", "common/js/spec_helpers/ajax_helpers", "squire"],
setup.call(this, requests)
# Delete the 2nd asset, but mimic a failure from the server.
@view.$(".remove-asset-button")[1].click()
@promptSpies.constructor.mostRecentCall.args[0].actions.primary.click(@promptSpies)
@promptSpies.constructor.calls.mostRecent().args[0].actions.primary.click(@promptSpies)
AjaxHelpers.respondWithError(requests)
expect(@view.$el).toContainText("test asset 1")
expect(@view.$el).toContainText("test asset 2")
@@ -319,7 +315,7 @@ define ["jquery", "jasmine", "common/js/spec_helpers/ajax_helpers", "squire"],
it "does not add an asset if asset already exists", ->
{view: @view, requests: requests} = @createAssetsView(this)
setup.call(this, requests)
spyOn(@collection, "add").andCallThrough()
spyOn(@collection, "add").and.callThrough()
model = @collection.models[1]
@view.addAsset(model)
expect(@collection.add).not.toHaveBeenCalled()

View File

@@ -47,16 +47,16 @@ define ["js/views/course_info_handout", "js/views/course_info_update", "js/model
# Edit button is not in the template under test (it is in parent HTML).
# Therefore call onNew directly.
@courseInfoEdit.onNew(@event)
spyOn(@courseInfoEdit.$codeMirror, 'getValue').andReturn(text)
spyOn(@courseInfoEdit.$codeMirror, 'getValue').and.returnValue(text)
@courseInfoEdit.$el.find('.save-button').click()
@cancelNewCourseInfo = (useCancelButton) ->
@courseInfoEdit.onNew(@event)
spyOn(@courseInfoEdit.$modalCover, 'hide').andCallThrough()
spyOn(@courseInfoEdit.$modalCover, 'hide').and.callThrough()
spyOn(@courseInfoEdit.$codeMirror, 'getValue').andReturn('unsaved changes')
spyOn(@courseInfoEdit.$codeMirror, 'getValue').and.returnValue('unsaved changes')
model = @collection.at(0)
spyOn(model, "save").andCallThrough()
spyOn(model, "save").and.callThrough()
cancelEditingUpdate(@courseInfoEdit, @courseInfoEdit.$modalCover, useCancelButton)
@@ -67,11 +67,11 @@ define ["js/views/course_info_handout", "js/views/course_info_update", "js/model
@doNotCloseNewCourseInfo = () ->
@courseInfoEdit.onNew(@event)
spyOn(@courseInfoEdit.$modalCover, 'hide').andCallThrough()
spyOn(@courseInfoEdit.$modalCover, 'hide').and.callThrough()
spyOn(@courseInfoEdit.$codeMirror, 'getValue').andReturn('unsaved changes')
spyOn(@courseInfoEdit.$codeMirror, 'getValue').and.returnValue('unsaved changes')
model = @collection.at(0)
spyOn(model, "save").andCallThrough()
spyOn(model, "save").and.callThrough()
cancelEditingUpdate(@courseInfoEdit, @courseInfoEdit.$modalCover, false)
@@ -81,11 +81,11 @@ define ["js/views/course_info_handout", "js/views/course_info_update", "js/model
@cancelExistingCourseInfo = (useCancelButton) ->
@createNewUpdate('existing update')
@courseInfoEdit.$el.find('.edit-button').click()
spyOn(@courseInfoEdit.$modalCover, 'hide').andCallThrough()
spyOn(@courseInfoEdit.$modalCover, 'hide').and.callThrough()
spyOn(@courseInfoEdit.$codeMirror, 'getValue').andReturn('modification')
spyOn(@courseInfoEdit.$codeMirror, 'getValue').and.returnValue('modification')
model = @collection.at(0)
spyOn(model, "save").andCallThrough()
spyOn(model, "save").and.callThrough()
model.id = "saved_to_server"
cancelEditingUpdate(@courseInfoEdit, @courseInfoEdit.$modalCover, useCancelButton)
@@ -94,6 +94,20 @@ define ["js/views/course_info_handout", "js/views/course_info_update", "js/model
previewContents = @courseInfoEdit.$el.find('.update-contents').html()
expect(previewContents).toEqual('existing update')
@testInvalidDateValue = (value) ->
@courseInfoEdit.onNew(@event)
expect(@courseInfoEdit.$el.find('.save-button').hasClass("is-disabled")).toEqual(false)
@courseInfoEdit.$el.find('input.date').val(value).trigger("change")
courseInfoEdit = @courseInfoEdit
jasmine.waitUntil(->
courseInfoEdit.$el.find('.save-button').hasClass('is-disabled') == true
).then ->
courseInfoEdit.$el.find('input.date').val('01/01/16').trigger 'change'
jasmine.waitUntil(->
courseInfoEdit.$el.find('.save-button').hasClass('is-disabled') == false
).always done
return
cancelEditingUpdate = (update, modalCover, useCancelButton) ->
if useCancelButton
update.$el.find('.cancel-button').click()
@@ -109,8 +123,8 @@ define ["js/views/course_info_handout", "js/views/course_info_update", "js/model
@courseInfoEdit.onNew(@event)
expect(@collection.length).toEqual(1)
model = @collection.at(0)
spyOn(model, "save").andCallThrough()
spyOn(@courseInfoEdit.$codeMirror, 'getValue').andReturn('/static/image.jpg')
spyOn(model, "save").and.callThrough()
spyOn(@courseInfoEdit.$codeMirror, 'getValue').and.returnValue('/static/image.jpg')
# Click the "Save button."
@courseInfoEdit.$el.find('.save-button').click()
@@ -153,14 +167,6 @@ define ["js/views/course_info_handout", "js/views/course_info_update", "js/model
it "does not remove existing course info on click outside modal", ->
@cancelExistingCourseInfo(false)
@testInvalidDateValue: (value) ->
@courseInfoEdit.onNew(@event)
expect(@courseInfoEdit.$el.find('.save-button').hasClass("is-disabled")).toEqual(false)
@courseInfoEdit.$el.find('input.date').val(value).trigger("change")
expect(@courseInfoEdit.$el.find('.save-button').hasClass("is-disabled")).toEqual(true)
@courseInfoEdit.$el.find('input.date').val("01/01/16").trigger("change")
expect(@courseInfoEdit.$el.find('.save-button').hasClass("is-disabled")).toEqual(false)
it "does not allow updates to be saved with an invalid date", ->
@testInvalidDateValue("Marchtober 40, 2048")
@@ -196,7 +202,7 @@ define ["js/views/course_info_handout", "js/views/course_info_update", "js/model
expect(requestSent.push_notification_selected).toEqual(true)
# Check that analytics send push_notification info
analytics_payload = window.analytics.track.calls[0].args[1]
analytics_payload = window.analytics.track.calls.first().args[1]
expect(analytics_payload).toEqual(jasmine.objectContaining({'push_notification_selected': true}))
it "sends correct value for push_notification_selected when it is unselected", ->
@@ -208,7 +214,7 @@ define ["js/views/course_info_handout", "js/views/course_info_update", "js/model
expect(requestSent.push_notification_selected).toEqual(false)
# Check that analytics send push_notification info
analytics_payload = window.analytics.track.calls[0].args[1]
analytics_payload = window.analytics.track.calls.first().args[1]
expect(analytics_payload).toEqual(jasmine.objectContaining({'push_notification_selected': false}))
describe "Course Handouts", ->
@@ -237,8 +243,8 @@ define ["js/views/course_info_handout", "js/views/course_info_update", "js/model
# Enter something in the handouts section, verifying that the model is saved
# when "Save" is clicked.
@handoutsEdit.$el.find('.edit-button').click()
spyOn(@handoutsEdit.$codeMirror, 'getValue').andReturn('/static/image.jpg')
spyOn(@model, "save").andCallThrough()
spyOn(@handoutsEdit.$codeMirror, 'getValue').and.returnValue('/static/image.jpg')
spyOn(@model, "save").and.callThrough()
@handoutsEdit.$el.find('.save-button').click()
expect(@model.save).toHaveBeenCalled()
@@ -251,7 +257,7 @@ define ["js/views/course_info_handout", "js/views/course_info_update", "js/model
it "does rewrite links after edit", ->
# Edit handouts and save.
@handoutsEdit.$el.find('.edit-button').click()
spyOn(@handoutsEdit.$codeMirror, 'getValue').andReturn('/static/image.jpg')
spyOn(@handoutsEdit.$codeMirror, 'getValue').and.returnValue('/static/image.jpg')
@handoutsEdit.$el.find('.save-button').click()
# Verify preview text.

View File

@@ -29,7 +29,7 @@ define ["jquery", "common/js/components/utils/view_utils", "js/spec_helpers/edit
</ul>
"""
edit_helpers.installEditTemplates(true);
spyOn($, 'ajax').andReturn(@moduleData)
spyOn($, 'ajax').and.returnValue(@moduleData)
@moduleEdit = new ModuleEdit(
el: $(".component")
@@ -62,7 +62,7 @@ define ["jquery", "common/js/components/utils/view_utils", "js/spec_helpers/edit
spyOn(@moduleEdit, 'loadDisplay')
spyOn(@moduleEdit, 'delegateEvents')
spyOn($.fn, 'append')
spyOn(ViewUtils, 'loadJavaScript').andReturn($.Deferred().resolve().promise());
spyOn(ViewUtils, 'loadJavaScript').and.returnValue($.Deferred().resolve().promise());
window.MockXBlock = (runtime, element) ->
return { }
@@ -70,7 +70,7 @@ define ["jquery", "common/js/components/utils/view_utils", "js/spec_helpers/edit
window.loadedXBlockResources = undefined
@moduleEdit.render()
$.ajax.mostRecentCall.args[0].success(
$.ajax.calls.mostRecent().args[0].success(
html: '<div>Response html</div>'
resources: [
['hash1', {kind: 'text', mimetype: 'text/css', data: 'inline-css'}],
@@ -120,7 +120,7 @@ define ["jquery", "common/js/components/utils/view_utils", "js/spec_helpers/edit
mockXBlockEditorHtml = readFixtures('mock/mock-xblock-editor.underscore')
$.ajax.mostRecentCall.args[0].success(
$.ajax.calls.mostRecent().args[0].success(
html: mockXBlockEditorHtml
resources: [
['hash1', {kind: 'text', mimetype: 'text/css', data: 'inline-css'}],
@@ -161,14 +161,14 @@ define ["jquery", "common/js/components/utils/view_utils", "js/spec_helpers/edit
expect($.fn.append).not.toHaveBeenCalledWith('not-head-html')
it "doesn't reload resources", ->
count = $('head').append.callCount
$.ajax.mostRecentCall.args[0].success(
count = $('head').append.calls.count()
$.ajax.calls.mostRecent().args[0].success(
html: '<div>Response html 2</div>'
resources: [
['hash1', {kind: 'text', mimetype: 'text/css', data: 'inline-css'}],
]
)
expect($('head').append.callCount).toBe(count)
expect($('head').append.calls.count()).toBe(count)
describe "loadDisplay", ->
beforeEach ->
@@ -177,4 +177,4 @@ define ["jquery", "common/js/components/utils/view_utils", "js/spec_helpers/edit
it "loads the .xmodule-display inside the module editor", ->
expect(XBlock.initializeBlock).toHaveBeenCalled()
expect(XBlock.initializeBlock.mostRecentCall.args[0]).toBe($('.xblock-student_view'))
expect(XBlock.initializeBlock.calls.mostRecent().args[0].get(0)).toBe($('.xblock-student_view').get(0))

View File

@@ -5,16 +5,6 @@ define ["js/models/textbook", "js/models/chapter", "js/collections/chapter", "js
"js/spec_helpers/modal_helpers", "jasmine-stealth"],
(Textbook, Chapter, ChapterSet, Course, TextbookSet, ShowTextbook, EditTextbook, ListTextbooks, EditChapter, Prompt, Notification, ViewUtils, AjaxHelpers, modal_helpers) ->
beforeEach ->
# remove this when we upgrade jasmine-jquery
@addMatchers
toContainText: (text) ->
trimmedText = $.trim(@actual.text())
if text and $.isFunction(text.test)
return text.test(trimmedText)
else
return trimmedText.indexOf(text) != -1;
describe "ShowTextbook", ->
tpl = readFixtures('show-textbook.underscore')
@@ -23,12 +13,12 @@ define ["js/models/textbook", "js/models/chapter", "js/collections/chapter", "js
appendSetFixtures(sandbox({id: "page-notification"}))
appendSetFixtures(sandbox({id: "page-prompt"}))
@model = new Textbook({name: "Life Sciences", id: "0life-sciences"})
spyOn(@model, "destroy").andCallThrough()
spyOn(@model, "destroy").and.callThrough()
@collection = new TextbookSet([@model])
@view = new ShowTextbook({model: @model})
@promptSpies = spyOnConstructor(Prompt, "Warning", ["show", "hide"])
@promptSpies.show.andReturn(@promptSpies)
@promptSpies = jasmine.stealth.spyOnConstructor(Prompt, "Warning", ["show", "hide"])
@promptSpies.show.and.returnValue(@promptSpies)
window.course = new Course({
id: "5",
name: "Course Name",
@@ -53,7 +43,7 @@ define ["js/models/textbook", "js/models/chapter", "js/collections/chapter", "js
it "should pop a delete confirmation when the delete button is clicked", ->
@view.render().$(".delete").click()
expect(@promptSpies.constructor).toHaveBeenCalled()
ctorOptions = @promptSpies.constructor.mostRecentCall.args[0]
ctorOptions = @promptSpies.constructor.calls.mostRecent().args[0]
expect(ctorOptions.title).toMatch(/Life Sciences/)
# hasn't actually been removed
expect(@model.destroy).not.toHaveBeenCalled()
@@ -73,9 +63,9 @@ define ["js/models/textbook", "js/models/chapter", "js/collections/chapter", "js
describe "AJAX", ->
beforeEach ->
@savingSpies = spyOnConstructor(Notification, "Mini",
@savingSpies = jasmine.stealth.spyOnConstructor(Notification, "Mini",
["show", "hide"])
@savingSpies.show.andReturn(@savingSpies)
@savingSpies.show.and.returnValue(@savingSpies)
CMS.URL.TEXTBOOKS = "/textbooks"
afterEach ->
@@ -85,7 +75,7 @@ define ["js/models/textbook", "js/models/chapter", "js/collections/chapter", "js
requests = AjaxHelpers["requests"](this)
@view.render().$(".delete").click()
ctorOptions = @promptSpies.constructor.mostRecentCall.args[0]
ctorOptions = @promptSpies.constructor.calls.mostRecent().args[0]
# run the primary function to indicate confirmation
ctorOptions.actions.primary.click(@promptSpies)
# AJAX request has been sent, but not yet returned
@@ -94,7 +84,7 @@ define ["js/models/textbook", "js/models/chapter", "js/collections/chapter", "js
expect(@savingSpies.constructor).toHaveBeenCalled()
expect(@savingSpies.show).toHaveBeenCalled()
expect(@savingSpies.hide).not.toHaveBeenCalled()
savingOptions = @savingSpies.constructor.mostRecentCall.args[0]
savingOptions = @savingSpies.constructor.calls.mostRecent().args[0]
expect(savingOptions.title).toMatch(/Deleting/)
# return a success response
requests[0].respond(200)
@@ -114,7 +104,7 @@ define ["js/models/textbook", "js/models/chapter", "js/collections/chapter", "js
@collection = new TextbookSet()
@collection.add(@model)
@view = new EditTextbook({model: @model})
spyOn(@view, 'render').andCallThrough()
spyOn(@view, 'render').and.callThrough()
it "should render properly", ->
@view.render()
@@ -209,10 +199,16 @@ define ["js/models/textbook", "js/models/chapter", "js/collections/chapter", "js
expect(ViewUtils.setScrollOffset).toHaveBeenCalledWith($sectionEl, 0)
it "should focus first input element of newly added textbook", ->
spyOn(jQuery.fn, 'focus').andCallThrough()
@addMatchers
toHaveBeenCalledOnJQueryObject: (actual, expected) ->
pass: actual.calls && actual.calls.mostRecent() && actual.calls.mostRecent().object[0] == expected[0]
spyOn(jQuery.fn, 'focus').and.callThrough()
jasmine.addMatchers
toHaveBeenCalledOnJQueryObject: () ->
return {
compare: (actual, expected) ->
return {
pass: actual.calls && actual.calls.mostRecent() &&
actual.calls.mostRecent().object[0] == expected[0]
}
}
@view.$(".new-button").click()
$inputEl = @view.$el.find('section:last input:first')
expect($inputEl.length).toEqual(1)
@@ -229,13 +225,13 @@ define ["js/models/textbook", "js/models/chapter", "js/collections/chapter", "js
# beforeEach ->
# setFixtures($("<script>", {id: "no-textbooks-tpl", type: "text/template"}).text(noTextbooksTpl))
# @showSpies = spyOnConstructor("ShowTextbook", ["render"])
# @showSpies.render.andReturn(@showSpies) # equivalent of `return this`
# @showSpies.render.and.returnValue(@showSpies) # equivalent of `return this`
# showEl = $("<li>")
# @showSpies.$el = showEl
# @showSpies.el = showEl.get(0)
# @editSpies = spyOnConstructor("EditTextbook", ["render"])
# editEl = $("<li>")
# @editSpies.render.andReturn(@editSpies)
# @editSpies.render.and.returnValue(@editSpies)
# @editSpies.$el = editEl
# @editSpies.el= editEl.get(0)
#
@@ -304,7 +300,7 @@ define ["js/models/textbook", "js/models/chapter", "js/collections/chapter", "js
@collection = new ChapterSet()
@collection.add(@model)
@view = new EditChapter({model: @model})
spyOn(@view, "remove").andCallThrough()
spyOn(@view, "remove").and.callThrough()
CMS.URL.UPLOAD_ASSET = "/upload"
window.course = new Course({name: "abcde"})
@@ -324,10 +320,10 @@ define ["js/models/textbook", "js/models/chapter", "js/collections/chapter", "js
# it "can open an upload dialog", ->
# uploadSpies = spyOnConstructor("UploadDialog", ["show", "el"])
# uploadSpies.show.andReturn(uploadSpies)
# uploadSpies.show.and.returnValue(uploadSpies)
#
# @view.render().$(".action-upload").click()
# ctorOptions = uploadSpies.constructor.mostRecentCall.args[0]
# ctorOptions = uploadSpies.constructor.calls.mostRecent().args[0]
# expect(ctorOptions.model.get('title')).toMatch(/abcde/)
# expect(typeof ctorOptions.onSuccess).toBe('function')
# expect(uploadSpies.show).toHaveBeenCalled()

View File

@@ -7,75 +7,80 @@ define ["js/models/uploads", "js/views/uploads", "js/models/chapter", "common/js
modal_helpers.installModalTemplates()
appendSetFixtures($("<script>", {id: "upload-dialog-tpl", type: "text/template"}).text(tpl))
CMS.URL.UPLOAD_ASSET = "/upload"
@model = new FileUpload(
mimeTypes: ['application/pdf']
)
@dialogResponse = dialogResponse = []
@view = new UploadDialog(
model: @model,
url: CMS.URL.UPLOAD_ASSET,
onSuccess: (response) =>
dialogResponse.push(response.response)
)
spyOn(@view, 'remove').andCallThrough()
# create mock file input, so that we aren't subject to browser restrictions
@mockFiles = []
mockFileInput = jasmine.createSpy('mockFileInput')
mockFileInput.files = @mockFiles
jqMockFileInput = jasmine.createSpyObj('jqMockFileInput', ['get', 'replaceWith'])
jqMockFileInput.get.andReturn(mockFileInput)
realMethod = @view.$
spyOn(@view, "$").andCallFake (selector) ->
if selector == "input[type=file]"
jqMockFileInput
else
realMethod.apply(this, arguments)
afterEach ->
delete CMS.URL.UPLOAD_ASSET
if (@view && modal_helpers.isShowingModal(@view))
@view.hide()
modal_helpers.cancelModalIfShowing()
createTestView = (test) ->
view = new UploadDialog(
model: test.model,
url: CMS.URL.UPLOAD_ASSET,
onSuccess: (response) =>
test.dialogResponse.push(response.response)
)
spyOn(view, 'remove').and.callThrough()
# create mock file input, so that we aren't subject to browser restrictions
mockFileInput = jasmine.createSpy('mockFileInput')
mockFileInput.files = test.mockFiles
jqMockFileInput = jasmine.createSpyObj('jqMockFileInput', ['get', 'replaceWith'])
jqMockFileInput.get.and.returnValue(mockFileInput)
originalView$ = view.$
spyOn(view, "$").and.callFake (selector) ->
if selector == "input[type=file]"
jqMockFileInput
else
originalView$.apply(this, arguments)
@lastView = view
describe "Basic", ->
it "should render without a file selected", ->
@view.render()
expect(@view.$el).toContain("input[type=file]")
expect(@view.$(".action-upload")).toHaveClass("disabled")
view = createTestView(this)
view.render()
expect(view.$el).toContainElement("input[type=file]")
expect(view.$(".action-upload")).toHaveClass("disabled")
it "should render with a PDF selected", ->
view = createTestView(this)
file = {name: "fake.pdf", "type": "application/pdf"}
@mockFiles.push(file)
@model.set("selectedFile", file)
@view.render()
expect(@view.$el).toContain("input[type=file]")
expect(@view.$el).not.toContain("#upload_error")
expect(@view.$(".action-upload")).not.toHaveClass("disabled")
view.render()
expect(view.$el).toContainElement("input[type=file]")
expect(view.$el).not.toContainElement("#upload_error")
expect(view.$(".action-upload")).not.toHaveClass("disabled")
it "should render an error with an invalid file type selected", ->
view = createTestView(this)
file = {name: "fake.png", "type": "image/png"}
@mockFiles.push(file)
@model.set("selectedFile", file)
@view.render()
expect(@view.$el).toContain("input[type=file]")
expect(@view.$el).toContain("#upload_error")
expect(@view.$(".action-upload")).toHaveClass("disabled")
view.render()
expect(view.$el).toContainElement("input[type=file]")
expect(view.$el).toContainElement("#upload_error")
expect(view.$(".action-upload")).toHaveClass("disabled")
it "should render an error with an invalid file type after a correct file type selected", ->
view = createTestView(this)
correctFile = {name: "fake.pdf", "type": "application/pdf"}
inCorrectFile = {name: "fake.png", "type": "image/png"}
event = {}
@view.render()
view.render()
event.target = {"files": [correctFile]}
@view.selectFile(event)
expect(@view.$el).toContain("input[type=file]")
expect(@view.$el).not.toContain("#upload_error")
expect(@view.$(".action-upload")).not.toHaveClass("disabled")
view.selectFile(event)
expect(view.$el).toContainElement("input[type=file]")
expect(view.$el).not.toContainElement("#upload_error")
expect(view.$(".action-upload")).not.toHaveClass("disabled")
realMethod = @model.set
spyOn(@model, "set").andCallFake (data) ->
spyOn(@model, "set").and.callFake (data) ->
if data.selectedFile != undefined
this.attributes.selectedFile = data.selectedFile
this.changed = {}
@@ -83,51 +88,46 @@ define ["js/models/uploads", "js/views/uploads", "js/models/chapter", "common/js
realMethod.apply(this, arguments)
event.target = {"files": [inCorrectFile]}
@view.selectFile(event)
expect(@view.$el).toContain("input[type=file]")
expect(@view.$el).toContain("#upload_error")
expect(@view.$(".action-upload")).toHaveClass("disabled")
view.selectFile(event)
expect(view.$el).toContainElement("input[type=file]")
expect(view.$el).toContainElement("#upload_error")
expect(view.$(".action-upload")).toHaveClass("disabled")
describe "Uploads", ->
beforeEach ->
@clock = sinon.useFakeTimers()
afterEach ->
modal_helpers.cancelModalIfShowing()
@clock.restore()
it "can upload correctly", ->
requests = AjaxHelpers["requests"](this)
@view.render()
@view.upload()
requests = AjaxHelpers.requests(this);
view = createTestView(this)
view.render()
view.upload()
expect(@model.get("uploading")).toBeTruthy()
expect(requests.length).toEqual(1)
request = requests[0]
expect(request.url).toEqual("/upload")
expect(request.method).toEqual("POST")
request.respond(200, {"Content-Type": "application/json"},
'{"response": "dummy_response"}')
AjaxHelpers.expectRequest(requests, "POST", "/upload")
AjaxHelpers.respondWithJson(requests, { response: "dummy_response"})
expect(@model.get("uploading")).toBeFalsy()
expect(@model.get("finished")).toBeTruthy()
expect(@dialogResponse.pop()).toEqual("dummy_response")
it "can handle upload errors", ->
requests = AjaxHelpers["requests"](this)
@view.render()
@view.upload()
requests[0].respond(500)
requests = AjaxHelpers.requests(this);
view = createTestView(this)
view.render()
view.upload()
AjaxHelpers.respondWithError(requests)
expect(@model.get("title")).toMatch(/error/)
expect(@view.remove).not.toHaveBeenCalled()
expect(view.remove).not.toHaveBeenCalled()
it "removes itself after two seconds on successful upload", ->
requests = AjaxHelpers["requests"](this)
@view.render()
@view.upload()
requests[0].respond(200, {"Content-Type": "application/json"},
'{"response": "dummy_response"}')
expect(modal_helpers.isShowingModal(@view)).toBeTruthy();
requests = AjaxHelpers.requests(this);
view = createTestView(this)
view.render()
view.upload()
AjaxHelpers.respondWithJson(requests, { response: "dummy_response"})
expect(modal_helpers.isShowingModal(view)).toBeTruthy();
@clock.tick(2001)
expect(modal_helpers.isShowingModal(@view)).toBeFalsy();
expect(modal_helpers.isShowingModal(view)).toBeFalsy();

View File

@@ -3,29 +3,21 @@
define(['jquery'], function($) { // jshint ignore:line
'use strict';
return function (that) {
that.addMatchers({
toContainText: function (text) {
// Assert the value being tested has text which matches the provided text
var trimmedText = $.trim($(this.actual).text());
if (text && $.isFunction(text.test)) {
return text.test(trimmedText);
} else {
return trimmedText.indexOf(text) !== -1;
}
},
toBeCorrectValuesInModel: function (values) {
return function () {
jasmine.addMatchers({
toBeCorrectValuesInModel: function () {
// Assert the value being tested has key values which match the provided values
return _.every(values, function (value, key) {
return this.actual.get(key) === value;
}.bind(this));
},
return {
compare: function (actual, values) {
var passed = _.every(values, function (value, key) {
return actual.get(key) === value;
}.bind(this));
toBeInstanceOf: function(expected) {
// Assert the type of the value being tested matches the provided type
return this.actual instanceof expected;
return {
pass: passed
};
}
};
}
});
};

View File

@@ -47,27 +47,6 @@ function(_, Course, CertificatesCollection, CertificateModel, CertificateDetails
ViewHelpers.verifyPromptHidden(promptSpy);
};
beforeEach(function() {
window.course = new Course({
id: '5',
name: 'Course Name',
url_name: 'course_name',
org: 'course_org',
num: 'course_num',
revision: 'course_rev'
});
window.certWebPreview = new CertificatePreview({
course_modes: ['honor', 'test'],
certificate_web_view_url: '/users/1/courses/orgX/009/2016'
});
window.CMS.User = {isGlobalStaff: true};
});
afterEach(function() {
delete window.course;
delete window.CMS.User;
});
describe('Certificate Details Spec:', function() {
var setValuesToInputs = function (view, values) {
_.each(values, function (value, selector) {
@@ -81,6 +60,20 @@ function(_, Course, CertificatesCollection, CertificateModel, CertificateDetails
beforeEach(function() {
TemplateHelpers.installTemplates(['certificate-details', 'signatory-details', 'signatory-editor', 'signatory-actions'], true);
window.course = new Course({
id: '5',
name: 'Course Name',
url_name: 'course_name',
org: 'course_org',
num: 'course_num',
revision: 'course_rev'
});
window.certWebPreview = new CertificatePreview({
course_modes: ['honor', 'test'],
certificate_web_view_url: '/users/1/courses/orgX/009/2016'
});
window.CMS.User = {isGlobalStaff: true};
this.newModelOptions = {add: true};
this.model = new CertificateModel({
name: 'Test Name',
@@ -97,7 +90,13 @@ function(_, Course, CertificatesCollection, CertificateModel, CertificateDetails
model: this.model
});
appendSetFixtures(this.view.render().el);
CustomMatchers(this); // jshint ignore:line
CustomMatchers(); // jshint ignore:line
});
afterEach(function() {
delete window.course;
delete window.certWebPreview;
delete window.CMS.User;
});
describe('The Certificate Details view', function() {

View File

@@ -18,7 +18,7 @@ function(_, Course, CertificateModel, SignatoryModel, CertificatesCollection, Ce
Notification, AjaxHelpers, TemplateHelpers, ViewHelpers, ValidationHelpers, CustomMatchers) {
'use strict';
var MAX_SIGNATORIES = 100;
var MAX_SIGNATORIES_LIMIT = 10;
var SELECTORS = {
detailsView: '.certificate-details',
editView: '.certificate-edit',
@@ -76,23 +76,6 @@ function(_, Course, CertificateModel, SignatoryModel, CertificatesCollection, Ce
AjaxHelpers.respondWithJson(requests, {asset: {url: file_path}});
};
beforeEach(function() {
window.course = new Course({
id: '5',
name: 'Course Name',
url_name: 'course_name',
org: 'course_org',
num: 'course_num',
revision: 'course_rev'
});
window.CMS.User = {isGlobalStaff: true};
});
afterEach(function() {
delete window.course;
delete window.CMS.User;
});
describe('Certificate editor view', function() {
var setValuesToInputs = function (view, values) {
_.each(values, function (value, selector) {
@@ -109,6 +92,16 @@ function(_, Course, CertificateModel, SignatoryModel, CertificatesCollection, Ce
beforeEach(function() {
TemplateHelpers.installTemplates(['certificate-editor', 'signatory-editor'], true);
window.course = new Course({
id: '5',
name: 'Course Name',
url_name: 'course_name',
org: 'course_org',
num: 'course_num',
revision: 'course_rev'
});
window.CMS.User = {isGlobalStaff: true};
this.newModelOptions = {add: true};
this.model = new CertificateModel({
name: 'Test Name',
@@ -122,10 +115,16 @@ function(_, Course, CertificateModel, SignatoryModel, CertificatesCollection, Ce
});
this.model.set('id', 0);
this.view = new CertificateEditorView({
model: this.model
model: this.model,
max_signatories_limit: MAX_SIGNATORIES_LIMIT
});
appendSetFixtures(this.view.render().el);
CustomMatchers(this); // jshint ignore:line
CustomMatchers(); // jshint ignore:line
});
afterEach(function() {
delete window.course;
delete window.CMS.User;
});
describe('Basic', function () {
@@ -198,8 +197,8 @@ function(_, Course, CertificateModel, SignatoryModel, CertificatesCollection, Ce
expect(this.collection.length).toBe(1);
});
it('user can only add signatories up to max 100', function() {
for(var i = 1; i < MAX_SIGNATORIES ; i++) {
it('user can only add signatories up to limit', function() {
for(var i = 1; i < MAX_SIGNATORIES_LIMIT ; i++) {
this.view.$(SELECTORS.addSignatoryButton).click();
}
expect(this.view.$(SELECTORS.addSignatoryButton)).toHaveClass('disableClick');
@@ -215,7 +214,7 @@ function(_, Course, CertificateModel, SignatoryModel, CertificatesCollection, Ce
it('user can add signatories when signatory reached the upper limit But after deleting a signatory',
function() {
for(var i = 1; i < MAX_SIGNATORIES ; i++) {
for(var i = 1; i < MAX_SIGNATORIES_LIMIT ; i++) {
this.view.$(SELECTORS.addSignatoryButton).click();
}
expect(this.view.$(SELECTORS.addSignatoryButton)).toHaveClass('disableClick');
@@ -274,7 +273,7 @@ function(_, Course, CertificateModel, SignatoryModel, CertificatesCollection, Ce
var signatory = this.model.get('signatories').at(0);
var signatory_url = '/certificates/signatory';
signatory.url = signatory_url;
spyOn(signatory, "isNew").andReturn(false);
spyOn(signatory, "isNew").and.returnValue(false);
var text = 'Delete "'+ signatory.get('name') +'" from the list of signatories?';
clickDeleteItem(this, text, SELECTORS.signatoryDeleteButton + ':first', signatory_url);
expect(this.model.get('signatories').length).toEqual(total_signatories - 1);
@@ -283,7 +282,7 @@ function(_, Course, CertificateModel, SignatoryModel, CertificatesCollection, Ce
it('can cancel deletion of signatories', function() {
this.view.$(SELECTORS.addSignatoryButton).click();
var signatory = this.model.get('signatories').at(0);
spyOn(signatory, "isNew").andReturn(false);
spyOn(signatory, "isNew").and.returnValue(false);
// add one more signatory
this.view.$(SELECTORS.addSignatoryButton).click();
var total_signatories = this.model.get('signatories').length;

View File

@@ -18,23 +18,6 @@ function(_, $, Course, CertificatePreview, TemplateHelpers, ViewHelpers, AjaxHel
preview_certificate: '.preview-certificate-link'
};
beforeEach(function() {
window.course = new Course({
id: '5',
name: 'Course Name',
url_name: 'course_name',
org: 'course_org',
num: 'course_num',
revision: 'course_rev'
});
window.CMS.User = {isGlobalStaff: true};
});
afterEach(function() {
delete window.course;
delete window.CMS.User;
});
describe('Certificate Web Preview Spec:', function() {
var selectDropDownByText = function ( element, value ) {
@@ -45,8 +28,18 @@ function(_, $, Course, CertificatePreview, TemplateHelpers, ViewHelpers, AjaxHel
};
beforeEach(function() {
TemplateHelpers.installTemplate('certificate-web-preview', true);
appendSetFixtures('<div class="preview-certificate nav-actions"></div>');
window.course = new Course({
id: '5',
name: 'Course Name',
url_name: 'course_name',
org: 'course_org',
num: 'course_num',
revision: 'course_rev'
});
window.CMS.User = {isGlobalStaff: true};
this.view = new CertificatePreview({
el: $('.preview-certificate'),
course_modes: ['test1', 'test2', 'test3'],
@@ -57,6 +50,11 @@ function(_, $, Course, CertificatePreview, TemplateHelpers, ViewHelpers, AjaxHel
appendSetFixtures(this.view.render().el);
});
afterEach(function() {
delete window.course;
delete window.CMS.User;
});
describe('Certificate preview', function() {
it('course mode event should call when user choose a new mode', function () {
spyOn(this.view, 'courseModeChanged');
@@ -122,7 +120,7 @@ function(_, $, Course, CertificatePreview, TemplateHelpers, ViewHelpers, AjaxHel
it('certificate web preview should be removed when method "remove" called', function () {
this.view.remove();
expect(this.view.el.innerHTML).toContain("");
expect(this.view.el.innerHTML).toBe('');
});
it('method "show" should call the render function', function () {

View File

@@ -27,33 +27,28 @@ function(_, Course, CertificatesCollection, CertificateModel, CertificateDetails
newCertificateButton: '.new-button'
};
beforeEach(function() {
window.course = new Course({
id: '5',
name: 'Course Name',
url_name: 'course_name',
org: 'course_org',
num: 'course_num',
revision: 'course_rev'
});
window.certWebPreview = new CertificatePreview({
course_modes: ['honor', 'test'],
certificate_web_view_url: '/users/1/courses/orgX/009/2016'
});
});
afterEach(function() {
delete window.course;
});
describe('Certificates list view', function() {
var emptyMessage = 'You have not created any certificates yet.';
beforeEach(function() {
TemplateHelpers.installTemplates(
['certificate-editor', 'certificate-edit', 'list']
['certificate-editor', 'list']
);
window.course = new Course({
id: '5',
name: 'Course Name',
url_name: 'course_name',
org: 'course_org',
num: 'course_num',
revision: 'course_rev'
});
window.certWebPreview = new CertificatePreview({
course_modes: ['honor', 'test'],
certificate_web_view_url: '/users/1/courses/orgX/009/2016'
});
window.CMS.User = {isGlobalStaff: true};
this.model = new CertificateModel({
course_title: 'Test Course Title Override'
}, {add: true});
@@ -61,11 +56,18 @@ function(_, Course, CertificatesCollection, CertificateModel, CertificateDetails
this.collection = new CertificatesCollection([], {
certificateUrl: '/certificates/'+ window.course.id
});
this.model.set('id', 0);
this.view = new CertificatesListView({
collection: this.collection
});
appendSetFixtures(this.view.render().el);
CustomMatchers(this); // jshint ignore:line
CustomMatchers(); // jshint ignore:line
});
afterEach(function() {
delete window.course;
delete window.certWebPreview;
delete window.CMS.User;
});
describe('empty template', function () {

View File

@@ -9,9 +9,11 @@ define([ // jshint ignore:line
'js/certificates/models/signatory',
'js/certificates/views/signatory_details',
'common/js/components/utils/view_utils',
'jquery.smoothScroll'
'jquery.smoothScroll',
'text!templates/certificate-details.underscore'
],
function($, _, str, gettext, BaseView, SignatoryModel, SignatoryDetailsView, ViewUtils) {
function($, _, str, gettext, BaseView, SignatoryModel, SignatoryDetailsView, ViewUtils, smoothScroll,
certificateDetailsTemplate) {
'use strict';
var CertificateDetailsView = BaseView.extend({
tagName: 'div',
@@ -31,7 +33,6 @@ function($, _, str, gettext, BaseView, SignatoryModel, SignatoryDetailsView, Vie
initialize: function() {
// Set up the initial state of the attributes set for this model instance
this.showDetails = true;
this.template = this.loadTemplate('certificate-details');
this.listenTo(this.model, 'change', this.render);
},
@@ -61,7 +62,7 @@ function($, _, str, gettext, BaseView, SignatoryModel, SignatoryDetailsView, Vie
index: this.model.collection.indexOf(this.model),
showDetails: this.showDetails || showDetails || false
});
this.$el.html(this.template(attrs));
this.$el.html(_.template(certificateDetailsTemplate)(attrs));
if(this.showDetails || showDetails) {
var self = this;
this.model.get("signatories").each(function (modelSignatory) {

View File

@@ -7,10 +7,11 @@ define([ // jshint ignore:line
'gettext',
'js/views/list_item_editor',
'js/certificates/models/signatory',
'js/certificates/views/signatory_editor'
'js/certificates/views/signatory_editor',
'text!templates/certificate-editor.underscore'
],
function($, _, Backbone, gettext,
ListItemEditorView, SignatoryModel, SignatoryEditorView) {
ListItemEditorView, SignatoryModel, SignatoryEditorView, certificateEditorTemplate) {
'use strict';
// If signatories limit is required to specific value then we can change it.
@@ -41,14 +42,15 @@ function($, _, Backbone, gettext,
].join(' ');
},
initialize: function() {
initialize: function(options) {
// Set up the initial state of the attributes set for this model instance
_.bindAll(this, "onSignatoryRemoved", "clearErrorMessage");
this.max_signatories_limit = options.max_signatories_limit || MAX_SIGNATORIES_LIMIT;
this.template = _.template(certificateEditorTemplate);
this.eventAgg = _.extend({}, Backbone.Events);
this.eventAgg.bind("onSignatoryRemoved", this.onSignatoryRemoved);
this.eventAgg.bind("onSignatoryUpdated", this.clearErrorMessage);
ListItemEditorView.prototype.initialize.call(this);
this.template = this.loadTemplate('certificate-editor');
},
onSignatoryRemoved: function() {
@@ -87,7 +89,7 @@ function($, _, Backbone, gettext,
disableAddSignatoryButton: function() {
// Disable the 'Add Signatory' link if the constraint has been met.
if(this.$(".signatory-edit-list > div.signatory-edit").length >= MAX_SIGNATORIES_LIMIT) {
if(this.$(".signatory-edit-list > div.signatory-edit").length >= this.max_signatories_limit) {
this.$(".action-add-signatory").addClass("disableClick");
}
},

View File

@@ -7,9 +7,10 @@ define([ // jshint ignore:line
'gettext',
'js/views/baseview',
'common/js/components/utils/view_utils',
'common/js/components/views/feedback_notification'
'common/js/components/views/feedback_notification',
"text!templates/certificate-web-preview.underscore"
],
function(_, gettext, BaseView, ViewUtils, NotificationView) {
function(_, gettext, BaseView, ViewUtils, NotificationView, certificateWebPreviewTemplate) {
'use strict';
var CertificateWebPreview = BaseView.extend({
el: $(".preview-certificate"),
@@ -23,11 +24,10 @@ function(_, gettext, BaseView, ViewUtils, NotificationView) {
this.certificate_web_view_url = options.certificate_web_view_url;
this.certificate_activation_handler_url = options.certificate_activation_handler_url;
this.is_active = options.is_active;
this.template = this.loadTemplate('certificate-web-preview');
},
render: function () {
this.$el.html(this.template({
this.$el.html(_.template(certificateWebPreviewTemplate)({
course_modes: this.course_modes,
certificate_web_view_url: this.certificate_web_view_url,
is_active: this.is_active

View File

@@ -9,9 +9,12 @@ define([ // jshint ignore:line
'js/utils/templates',
'common/js/components/utils/view_utils',
'js/views/baseview',
'js/certificates/views/signatory_editor'
'js/certificates/views/signatory_editor',
'text!templates/signatory-details.underscore',
'text!templates/signatory-actions.underscore'
],
function ($, _, str, Backbone, gettext, TemplateUtils, ViewUtils, BaseView, SignatoryEditorView) {
function ($, _, str, Backbone, gettext, TemplateUtils, ViewUtils, BaseView, SignatoryEditorView,
signatoryDetailsTemplate, signatoryActionsTemplate) {
'use strict';
var SignatoryDetailsView = BaseView.extend({
tagName: 'div',
@@ -39,8 +42,6 @@ function ($, _, str, Backbone, gettext, TemplateUtils, ViewUtils, BaseView, Sign
isEditingAllCollections: false,
eventAgg: this.eventAgg
});
this.template = this.loadTemplate('signatory-details');
this.signatory_action_template = this.loadTemplate('signatory-actions');
},
loadTemplate: function(name) {
@@ -52,7 +53,7 @@ function ($, _, str, Backbone, gettext, TemplateUtils, ViewUtils, BaseView, Sign
// Retrieve the edit view for this model
if (event && event.preventDefault) { event.preventDefault(); }
this.$el.html(this.edit_view.render());
$(this.signatory_action_template()).appendTo(this.el);
$(_.template(signatoryActionsTemplate)()).appendTo(this.el);
this.edit_view.delegateEvents();
this.delegateEvents();
},
@@ -93,7 +94,7 @@ function ($, _, str, Backbone, gettext, TemplateUtils, ViewUtils, BaseView, Sign
var attributes = $.extend({}, this.model.attributes, {
signatory_number: this.model.collection.indexOf(this.model) + 1
});
return $(this.el).html(this.template(attributes));
return $(this.el).html(_.template(signatoryDetailsTemplate)(attributes));
}
});
return SignatoryDetailsView;

View File

@@ -10,10 +10,12 @@ define([ // jshint ignore:line
'common/js/components/views/feedback_prompt',
'common/js/components/views/feedback_notification',
'js/models/uploads',
'js/views/uploads'
'js/views/uploads',
'text!templates/signatory-editor.underscore'
],
function ($, _, Backbone, gettext,
TemplateUtils, ViewUtils, PromptView, NotificationView, FileUploadModel, FileUploadDialog) {
TemplateUtils, ViewUtils, PromptView, NotificationView, FileUploadModel, FileUploadDialog,
signatoryEditorTemplate) {
'use strict';
var SignatoryEditorView = Backbone.View.extend({
tagName: 'div',
@@ -41,7 +43,6 @@ function ($, _, Backbone, gettext,
this.model.bind('change', this.render);
this.eventAgg = options.eventAgg;
this.isEditingAllCollections = options.isEditingAllCollections;
this.template = this.loadTemplate('signatory-editor');
},
getModelIndex: function(givenModel) {
@@ -77,7 +78,7 @@ function ($, _, Backbone, gettext,
is_editing_all_collections: this.isEditingAllCollections,
total_saved_signatories: this.getTotalSignatoriesOnServer()
});
return $(this.el).html(this.template(attributes));
return $(this.el).html(_.template(signatoryEditorTemplate)(attributes));
},
setSignatoryName: function(event) {

View File

@@ -1,41 +1,29 @@
define([
'backbone', 'coffee/src/main', 'js/models/group_configuration',
'js/models/group', 'js/collections/group', 'squire'
], function(
Backbone, main, GroupConfigurationModel, GroupModel, GroupCollection, Squire
) {
], function (Backbone, main, GroupConfigurationModel, GroupModel, GroupCollection, Squire) {
'use strict';
beforeEach(function() {
this.addMatchers({
toBeInstanceOf: function(expected) {
return this.actual instanceof expected;
},
toBeEmpty: function() {
return this.actual.length === 0;
}
});
});
describe('GroupConfigurationModel', function() {
beforeEach(function() {
describe('GroupConfigurationModel', function () {
beforeEach(function () {
main();
this.model = new GroupConfigurationModel();
});
describe('Basic', function() {
it('should have an empty name by default', function() {
describe('Basic', function () {
it('should have an empty name by default', function () {
expect(this.model.get('name')).toEqual('');
});
it('should have an empty description by default', function() {
it('should have an empty description by default', function () {
expect(this.model.get('description')).toEqual('');
});
it('should not show groups by default', function() {
it('should not show groups by default', function () {
expect(this.model.get('showGroups')).toBeFalsy();
});
it('should have a collection with 2 groups by default', function() {
it('should have a collection with 2 groups by default', function () {
var groups = this.model.get('groups');
expect(groups).toBeInstanceOf(GroupCollection);
@@ -43,11 +31,11 @@ define([
expect(groups.at(1).get('name')).toBe('Group B');
});
it('should have an empty usage by default', function() {
expect(this.model.get('usage')).toBeEmpty();
it('should have an empty usage by default', function () {
expect(this.model.get('usage').length).toBe(0);
});
it('should be able to reset itself', function() {
it('should be able to reset itself', function () {
var originalName = 'Original Name',
model = new GroupConfigurationModel({name: originalName});
model.set({name: 'New Name'});
@@ -56,18 +44,18 @@ define([
expect(model.get('name')).toEqual(originalName);
});
it('should be dirty after it\'s been changed', function() {
it('should be dirty after it\'s been changed', function () {
this.model.set('name', 'foobar');
expect(this.model.isDirty()).toBeTruthy();
});
describe('should not be dirty', function () {
it('by default', function() {
it('by default', function () {
expect(this.model.isDirty()).toBeFalsy();
});
it('after calling setOriginalAttributes', function() {
it('after calling setOriginalAttributes', function () {
this.model.set('name', 'foobar');
this.model.setOriginalAttributes();
@@ -76,13 +64,13 @@ define([
});
});
describe('Input/Output', function() {
var deepAttributes = function(obj) {
describe('Input/Output', function () {
var deepAttributes = function (obj) {
if (obj instanceof Backbone.Model) {
return deepAttributes(obj.attributes);
} else if (obj instanceof Backbone.Collection) {
return obj.map(deepAttributes);
} else if (_.isObject(obj)) {
} else if ($.isPlainObject(obj)) {
var attributes = {};
for (var prop in obj) {
@@ -96,7 +84,7 @@ define([
}
};
it('should match server model to client model', function() {
it('should match server model to client model', function () {
var serverModelSpec = {
'id': 10,
'name': 'My Group Configuration',
@@ -139,32 +127,32 @@ define([
'usage': []
},
model = new GroupConfigurationModel(
serverModelSpec, { parse: true }
serverModelSpec, {parse: true}
);
expect(deepAttributes(model)).toEqual(clientModelSpec);
expect(model.toJSON()).toEqual(serverModelSpec);
expect(JSON.parse(JSON.stringify(model))).toEqual(serverModelSpec);
});
});
describe('Validation', function() {
it('requires a name', function() {
var model = new GroupConfigurationModel({ name: '' });
describe('Validation', function () {
it('requires a name', function () {
var model = new GroupConfigurationModel({name: ''});
expect(model.isValid()).toBeFalsy();
});
it('can pass validation', function() {
it('can pass validation', function () {
// Note that two groups - Group A and Group B - are
// created by default.
var model = new GroupConfigurationModel({ name: 'foo' });
var model = new GroupConfigurationModel({name: 'foo'});
expect(model.isValid()).toBeTruthy();
});
it('requires at least one group', function() {
var group1 = new GroupModel({ name: 'Group A' }),
model = new GroupConfigurationModel({ name: 'foo', groups: [] });
it('requires at least one group', function () {
var group1 = new GroupModel({name: 'Group A'}),
model = new GroupConfigurationModel({name: 'foo', groups: []});
expect(model.isValid()).toBeFalsy();
@@ -172,21 +160,21 @@ define([
expect(model.isValid()).toBeTruthy();
});
it('requires a valid group', function() {
var model = new GroupConfigurationModel({ name: 'foo', groups: [{ name: '' }] });
it('requires a valid group', function () {
var model = new GroupConfigurationModel({name: 'foo', groups: [{name: ''}]});
expect(model.isValid()).toBeFalsy();
});
it('requires all groups to be valid', function() {
var model = new GroupConfigurationModel({ name: 'foo', groups: [{ name: 'Group A' }, { name: '' }] });
it('requires all groups to be valid', function () {
var model = new GroupConfigurationModel({name: 'foo', groups: [{name: 'Group A'}, {name: ''}]});
expect(model.isValid()).toBeFalsy();
});
it('requires all groups to have unique names', function() {
it('requires all groups to have unique names', function () {
var model = new GroupConfigurationModel({
name: 'foo', groups: [{ name: 'Group A' }, { name: 'Group A' }]
name: 'foo', groups: [{name: 'Group A'}, {name: 'Group A'}]
});
expect(model.isValid()).toBeFalsy();
@@ -194,91 +182,92 @@ define([
});
});
describe('GroupModel', function() {
beforeEach(function() {
describe('GroupModel', function () {
beforeEach(function () {
this.collection = new GroupCollection([{}]);
this.model = this.collection.at(0);
});
describe('Basic', function() {
it('should have an empty name by default', function() {
describe('Basic', function () {
it('should have an empty name by default', function () {
expect(this.model.get('name')).toEqual('');
});
it('should be empty by default', function() {
it('should be empty by default', function () {
expect(this.model.isEmpty()).toBeTruthy();
});
});
describe('Validation', function() {
it('requires a name', function() {
var model = new GroupModel({ name: '' });
describe('Validation', function () {
it('requires a name', function () {
var model = new GroupModel({name: ''});
expect(model.isValid()).toBeFalsy();
});
it('can pass validation', function() {
var model = new GroupConfigurationModel({ name: 'foo' });
it('can pass validation', function () {
var model = new GroupConfigurationModel({name: 'foo'});
expect(model.isValid()).toBeTruthy();
});
});
});
describe('GroupCollection', function() {
beforeEach(function() {
describe('GroupCollection', function () {
beforeEach(function () {
this.collection = new GroupCollection();
});
it('is empty by default', function() {
it('is empty by default', function () {
expect(this.collection.isEmpty()).toBeTruthy();
});
it('is empty if all groups are empty', function() {
this.collection.add([{ name: '' }, { name: '' }, { name: '' }]);
it('is empty if all groups are empty', function () {
this.collection.add([{name: ''}, {name: ''}, {name: ''}]);
expect(this.collection.isEmpty()).toBeTruthy();
});
it('is not empty if a group is not empty', function() {
it('is not empty if a group is not empty', function () {
this.collection.add([
{ name: '' }, { name: 'full' }, { name: '' }
{name: ''}, {name: 'full'}, {name: ''}
]);
expect(this.collection.isEmpty()).toBeFalsy();
});
describe('getGroupId', function () {
var collection, injector, mockGettext, initializeGroupModel;
var collection, injector, mockGettext, initializeGroupModel, cleanUp;
mockGettext = function (returnedValue) {
var injector = new Squire();
injector.mock('gettext', function () {
return function () { return returnedValue; };
return function () {
return returnedValue;
};
});
return injector;
};
initializeGroupModel = function (dict, that) {
runs(function() {
injector = mockGettext(dict);
injector.require(['js/collections/group'],
function(GroupCollection) {
initializeGroupModel = function (dict) {
var deferred = $.Deferred();
injector = mockGettext(dict);
injector.require(['js/collections/group'],
function (GroupCollection) {
collection = new GroupCollection();
deferred.resolve(collection);
});
});
waitsFor(function() {
return collection;
}, 'GroupModel was not instantiated', 500);
return deferred.promise();
};
that.after(function () {
collection = null;
injector.clean();
injector.remove();
});
cleanUp = function () {
collection = null;
injector.clean();
injector.remove();
};
it('returns correct ids', function () {
@@ -294,34 +283,46 @@ define([
expect(collection.getGroupId(475279)).toBe('AAAAZ');
});
it('just 1 character in the dictionary', function () {
initializeGroupModel('1', this);
runs(function() {
expect(collection.getGroupId(0)).toBe('1');
expect(collection.getGroupId(1)).toBe('11');
expect(collection.getGroupId(5)).toBe('111111');
});
it('just 1 character in the dictionary', function (done) {
initializeGroupModel('1')
.then(function (collection) {
expect(collection.getGroupId(0)).toBe('1');
expect(collection.getGroupId(1)).toBe('11');
expect(collection.getGroupId(5)).toBe('111111');
})
.always(function () {
cleanUp();
done();
});
});
it('allow to use unicode characters in the dict', function () {
initializeGroupModel('ö诶úeœ', this);
runs(function() {
expect(collection.getGroupId(0)).toBe('ö');
expect(collection.getGroupId(1)).toBe('诶');
expect(collection.getGroupId(5)).toBe('öö');
expect(collection.getGroupId(29)).toBe('œœ');
expect(collection.getGroupId(30)).toBe('ööö');
expect(collection.getGroupId(43)).toBe('öúe');
});
it('allow to use unicode characters in the dict', function (done) {
initializeGroupModel('ö诶úeœ')
.then(function (collection) {
expect(collection.getGroupId(0)).toBe('ö');
expect(collection.getGroupId(1)).toBe('诶');
expect(collection.getGroupId(5)).toBe('öö');
expect(collection.getGroupId(29)).toBe('œœ');
expect(collection.getGroupId(30)).toBe('ööö');
expect(collection.getGroupId(43)).toBe('öúe');
})
.always(function () {
cleanUp();
done();
});
});
it('return initial value if dictionary is empty', function () {
initializeGroupModel('', this);
runs(function() {
expect(collection.getGroupId(0)).toBe('0');
expect(collection.getGroupId(5)).toBe('5');
expect(collection.getGroupId(30)).toBe('30');
});
it('return initial value if dictionary is empty', function (done) {
initializeGroupModel('')
.then(function (collection) {
expect(collection.getGroupId(0)).toBe('0');
expect(collection.getGroupId(5)).toBe('5');
expect(collection.getGroupId(30)).toBe('30');
})
.always(function () {
cleanUp();
done();
});
});
});
});

View File

@@ -40,7 +40,7 @@ define(["js/utils/drag_and_drop", "common/js/components/views/feedback_notificat
left: $ele.offset().left
});
destination = ContentDragger.findDestination($ele, 1);
expect(destination.ele).toBe($('#unit-2'));
expect(destination.ele).toEqual($('#unit-2'));
expect(destination.attachMethod).toBe('before');
});
it("can drag and drop across section boundaries, with special handling for single sibling", function () {
@@ -52,17 +52,17 @@ define(["js/utils/drag_and_drop", "common/js/components/views/feedback_notificat
left: $ele.offset().left
});
destination = ContentDragger.findDestination($ele, 1);
expect(destination.ele).toBe($unit4);
expect(destination.ele).toEqual($unit4);
expect(destination.attachMethod).toBe('after');
destination = ContentDragger.findDestination($ele, -1);
expect(destination.ele).toBe($unit4);
expect(destination.ele).toEqual($unit4);
expect(destination.attachMethod).toBe('before');
$ele.offset({
top: $unit4.offset().top + $unit4.height() + 1,
left: $ele.offset().left
});
destination = ContentDragger.findDestination($ele, 0);
expect(destination.ele).toBe($unit4);
expect(destination.ele).toEqual($unit4);
expect(destination.attachMethod).toBe('after');
$unit0 = $('#unit-0');
$ele.offset({
@@ -70,7 +70,7 @@ define(["js/utils/drag_and_drop", "common/js/components/views/feedback_notificat
left: $ele.offset().left
});
destination = ContentDragger.findDestination($ele, 0);
expect(destination.ele).toBe($unit0);
expect(destination.ele).toEqual($unit0);
expect(destination.attachMethod).toBe('before');
});
it("can drop before the first element, even if element being dragged is\nslightly before the first element", function () {
@@ -81,7 +81,7 @@ define(["js/utils/drag_and_drop", "common/js/components/views/feedback_notificat
left: $ele.offset().left
});
destination = ContentDragger.findDestination($ele, -1);
expect(destination.ele).toBe($('#subsection-0'));
expect(destination.ele).toEqual($('#subsection-0'));
expect(destination.attachMethod).toBe('before');
});
it("can drag and drop across section boundaries, with special handling for last element", function () {
@@ -92,14 +92,14 @@ define(["js/utils/drag_and_drop", "common/js/components/views/feedback_notificat
left: $ele.offset().left
});
destination = ContentDragger.findDestination($ele, -1);
expect(destination.ele).toBe($('#unit-3'));
expect(destination.ele).toEqual($('#unit-3'));
expect(destination.attachMethod).toBe('after');
$ele.offset({
top: $('#unit-3').offset().top + 4,
left: $ele.offset().left
});
destination = ContentDragger.findDestination($ele, -1);
expect(destination.ele).toBe($('#unit-3'));
expect(destination.ele).toEqual($('#unit-3'));
expect(destination.attachMethod).toBe('before');
});
it("can drop past the last element, even if element being dragged is\nslightly before/taller then the last element", function () {
@@ -110,7 +110,7 @@ define(["js/utils/drag_and_drop", "common/js/components/views/feedback_notificat
left: $ele.offset().left
});
destination = ContentDragger.findDestination($ele, 1);
expect(destination.ele).toBe($('#subsection-4'));
expect(destination.ele).toEqual($('#subsection-4'));
expect(destination.attachMethod).toBe('after');
});
it("can drag into an empty list", function () {
@@ -121,7 +121,7 @@ define(["js/utils/drag_and_drop", "common/js/components/views/feedback_notificat
left: $ele.offset().left
});
destination = ContentDragger.findDestination($ele, 1);
expect(destination.ele).toBe($('#subsection-list-3'));
expect(destination.ele).toEqual($('#subsection-list-3'));
expect(destination.attachMethod).toBe('prepend');
});
it("reports a null destination on a failed drag", function () {
@@ -146,8 +146,8 @@ define(["js/utils/drag_and_drop", "common/js/components/views/feedback_notificat
left: $ele.offset().left
});
destination = ContentDragger.findDestination($ele, 1);
expect(destination.ele).toBe($('#subsection-list-2'));
expect(destination.parentList).toBe($('#subsection-2'));
expect(destination.ele).toEqual($('#subsection-list-2'));
expect(destination.parentList).toEqual($('#subsection-2'));
expect(destination.attachMethod).toBe('prepend');
});
});
@@ -176,7 +176,7 @@ define(["js/utils/drag_and_drop", "common/js/components/views/feedback_notificat
});
describe("onDragMove", function () {
beforeEach(function () {
this.redirectSpy = spyOn(window, 'scrollBy').andCallThrough();
this.redirectSpy = spyOn(window, 'scrollBy').and.callThrough();
});
it("adds the correct CSS class to the drop destination", function () {
var $ele, dragX, dragY;
@@ -239,7 +239,7 @@ define(["js/utils/drag_and_drop", "common/js/components/views/feedback_notificat
this.reorderSpy = spyOn(ContentDragger, 'handleReorder');
});
afterEach(function () {
this.reorderSpy.reset();
this.reorderSpy.calls.reset();
});
it("calls handleReorder on a successful drag", function () {
ContentDragger.dragState.dropDestination = $('#unit-2');
@@ -279,7 +279,7 @@ define(["js/utils/drag_and_drop", "common/js/components/views/feedback_notificat
expect($('#subsection-1')).not.toHaveClass('expand-on-drop');
});
it("expands a collapsed element when something is dropped in it", function () {
expandElementSpy = spyOn(ContentDragger, 'expandElement').andCallThrough();
var expandElementSpy = spyOn(ContentDragger, 'expandElement').and.callThrough();
expect(expandElementSpy).not.toHaveBeenCalled();
expect($('#subsection-2').data('ensureChildrenRendered')).not.toHaveBeenCalled();
@@ -301,8 +301,8 @@ define(["js/utils/drag_and_drop", "common/js/components/views/feedback_notificat
});
describe("AJAX", function () {
beforeEach(function () {
this.savingSpies = spyOnConstructor(Notification, "Mini", ["show", "hide"]);
this.savingSpies.show.andReturn(this.savingSpies);
this.savingSpies = jasmine.stealth.spyOnConstructor(Notification, "Mini", ["show", "hide"]);
this.savingSpies.show.and.returnValue(this.savingSpies);
this.clock = sinon.useFakeTimers();
});
afterEach(function () {
@@ -327,7 +327,7 @@ define(["js/utils/drag_and_drop", "common/js/components/views/feedback_notificat
expect(this.savingSpies.constructor).toHaveBeenCalled();
expect(this.savingSpies.show).toHaveBeenCalled();
expect(this.savingSpies.hide).not.toHaveBeenCalled();
savingOptions = this.savingSpies.constructor.mostRecentCall.args[0];
savingOptions = this.savingSpies.constructor.calls.mostRecent().args[0];
expect(savingOptions.title).toMatch(/Saving/);
expect($('#unit-1')).toHaveClass('was-dropped');
expect(request.requestBody).toEqual('{"children":["fourth-unit-id","first-unit-id"]}');

View File

@@ -39,7 +39,9 @@ function ($, _, IframeBinding) {
//after calling iframeBinding function: src url of iframes should have "wmode=transparent" in its querystring
//and embed objects should have "wmode='transparent'" as an attribute
expect(iframe_html).toContain('<iframe src="http://www.youtube.com/embed/NHd27UvY-lw?wmode=transparent"');
expect(iframe_html).toContain('<embed wmode="transparent" type="application/x-shockwave-flash" src="http://www.youtube.com/embed/NHd27UvY-lw"');
expect(iframe_html).toContainHtml(
'<embed wmode="transparent" type="application/x-shockwave-flash"' +
' src="http://www.youtube.com/embed/NHd27UvY-lw"');
});
it("does not modify src url of DOM iframe if it is empty", function () {

View File

@@ -30,61 +30,104 @@ function ($, _, Squire) {
var createPromptSpy = function (name) {
var spy = jasmine.createSpyObj(name, ['constructor', 'show', 'hide']);
spy.constructor.andReturn(spy);
spy.show.andReturn(spy);
spy.extend = jasmine.createSpy().andReturn(spy.constructor);
spy.constructor.and.returnValue(spy);
spy.show.and.returnValue(spy);
spy.extend = jasmine.createSpy().and.returnValue(spy.constructor);
return spy;
};
beforeEach(function () {
beforeEach(function (done) {
self = this;
this.addMatchers({
assertValueInView: function(expected) {
var value = this.actual.getValueFromEditor();
return this.env.equals_(value, expected);
jasmine.addMatchers({
assertValueInView: function() {
return {
compare: function (actual, expected) {
var value = actual.getValueFromEditor(),
passed = _.isEqual(value, expected);
return {
pass: passed,
message: 'Expected ' + actual + (passed ? '' : ' not') + ' to equal ' + expected
};
}
};
},
assertCanUpdateView: function (expected) {
var view = this.actual,
value;
assertCanUpdateView: function () {
return {
compare: function (actual, expected) {
var view = actual,
value,
passed;
view.setValueInEditor(expected);
value = view.getValueFromEditor();
view.setValueInEditor(expected);
value = view.getValueFromEditor();
return this.env.equals_(value, expected);
passed = _.isEqual(value, expected);
return {
pass: passed,
message: 'Expected ' + actual + (passed ? '' : ' not') + ' to equal ' + expected
};
}
};
},
assertClear: function (modelValue) {
var env = this.env,
view = this.actual,
model = view.model;
assertClear: function () {
return {
compare: function (actual, modelValue) {
var view = actual,
model = view.model,
passed;
return model.getValue() === null &&
env.equals_(model.getDisplayValue(), modelValue) &&
env.equals_(view.getValueFromEditor(), modelValue);
passed = model.getValue() === null &&
_.isEqual(model.getDisplayValue(), modelValue) &&
_.isEqual(view.getValueFromEditor(), modelValue);
return {
pass: passed
};
}
};
},
assertUpdateModel: function (originalValue, newValue) {
var env = this.env,
view = this.actual,
model = view.model,
expectOriginal;
assertUpdateModel: function () {
return {
compare: function (actual, originalValue, newValue) {
var view = actual,
model = view.model,
expectOriginal,
passed;
view.setValueInEditor(newValue);
expectOriginal = env.equals_(model.getValue(), originalValue);
view.updateModel();
view.setValueInEditor(newValue);
expectOriginal = _.isEqual(model.getValue(), originalValue);
view.updateModel();
return expectOriginal &&
env.equals_(model.getValue(), newValue);
passed = expectOriginal &&
_.isEqual(model.getValue(), newValue);
return {
pass: passed
};
}
};
},
verifyButtons: function (upload, download, index) {
var view = this.actual,
uploadBtn = view.$('.upload-setting'),
downloadBtn = view.$('.download-setting');
verifyButtons: function () {
return {
compare: function (actual, upload, download) {
var view = actual,
uploadBtn = view.$('.upload-setting'),
downloadBtn = view.$('.download-setting'),
passed;
upload = upload ? uploadBtn.length : !uploadBtn.length;
download = download ? downloadBtn.length : !downloadBtn.length;
upload = upload ? uploadBtn.length : !uploadBtn.length;
download = download ? downloadBtn.length : !downloadBtn.length;
passed = upload && download;
return upload && download;
return {
pass: passed
};
}
};
}
});
@@ -107,22 +150,18 @@ function ($, _, Squire) {
injector.mock('js/views/video/transcripts/metadata_videolist');
injector.mock('js/views/video/translations_editor');
runs(function() {
injector.require([
injector.require([
'js/models/metadata', 'js/views/metadata'
],
function(MetadataModel, MetadataView) {
function (MetadataModel, MetadataView) {
var model = new MetadataModel($.extend(true, {}, modelStub));
self.view = new MetadataView.FileUploader({
model: model,
locator: locator
});
});
});
waitsFor(function() {
return self.view;
}, 'FileUploader was not created', 2000);
done();
});
});
afterEach(function () {
@@ -150,7 +189,7 @@ function ($, _, Squire) {
expect(this.uploadSpies.constructor).toHaveBeenCalled();
expect(this.uploadSpies.show).toHaveBeenCalled();
options = this.uploadSpies.constructor.mostRecentCall.args[0];
options = this.uploadSpies.constructor.calls.mostRecent().args[0];
options.onSuccess({
'asset': {
'url': 'http://example.org/test_3'

View File

@@ -3,8 +3,7 @@ define(
"jquery", "backbone", "underscore",
"js/views/video/transcripts/utils", "js/views/video/transcripts/editor",
"js/views/metadata", "js/models/metadata", "js/collections/metadata",
"underscore.string", "xmodule", "js/views/video/transcripts/metadata_videolist",
"jasmine-jquery"
"underscore.string", "xmodule", "js/views/video/transcripts/metadata_videolist"
],
function ($, Backbone, _, Utils, Editor, MetadataView, MetadataModel, MetadataCollection, _str) {
describe('Transcripts.Editor', function () {
@@ -43,6 +42,13 @@ function ($, Backbone, _, Utils, Editor, MetadataView, MetadataModel, MetadataCo
},
transcripts, container;
var waitsForDisplayName = function (collection) {
return jasmine.waitUntil(function () {
var displayNameValue = collection[0].getValue();
return displayNameValue !== '' && displayNameValue !== 'video_id';
});
};
beforeEach(function () {
var tpl = sandbox({
'class': 'wrapper-comp-settings basic_metadata_edit',
@@ -60,7 +66,6 @@ function ($, Backbone, _, Utils, Editor, MetadataView, MetadataModel, MetadataCo
});
describe('Test initialization', function () {
beforeEach(function () {
spyOn(MetadataView, 'Editor');
@@ -158,27 +163,23 @@ function ($, Backbone, _, Utils, Editor, MetadataView, MetadataModel, MetadataCo
});
describe('Test Advanced to Basic synchronization', function () {
it('Correct data', function () {
it('Correct data', function (done) {
transcripts.syncBasicTab(metadataCollection, metadataView);
var collection = transcripts.collection.models;
waitsFor(function() {
var displayNameValue = collection[0].getValue();
return (displayNameValue !== "" && displayNameValue != "video_id");
}, "Defaults never loaded", 1000);
waitsForDisplayName(collection)
.then(function () {
var displayNameValue = collection[0].getValue(),
videoUrlValue = collection[1].getValue();
runs(function() {
var displayNameValue = collection[0].getValue(),
videoUrlValue = collection[1].getValue();
expect(displayNameValue).toEqual('default');
expect(videoUrlValue).toEqual([
'http://youtu.be/OEoXaMPEzfM',
'default.mp4',
'default.webm'
]);
});
expect(displayNameValue).toEqual('default');
expect(videoUrlValue).toEqual([
'http://youtu.be/OEoXaMPEzfM',
'default.mp4',
'default.webm'
]);
})
.always(done);
});
it('If metadataCollection is not defined', function () {
@@ -219,31 +220,26 @@ function ($, Backbone, _, Utils, Editor, MetadataView, MetadataModel, MetadataCo
});
describe('Test Basic to Advanced synchronization', function () {
it('Correct data', function () {
it('Correct data', function (done) {
transcripts.syncAdvancedTab(metadataCollection);
var collection = metadataCollection.models;
waitsForDisplayName(collection)
.then(function () {
var displayNameValue = collection[0].getValue();
var subValue = collection[1].getValue();
var html5SourcesValue = collection[2].getValue();
var youtubeValue = collection[3].getValue();
waitsFor(function() {
var displayNameValue = collection[0].getValue();
return (displayNameValue !== "" && displayNameValue != "video_id");
}, "Defaults never loaded", 1000);
runs(function() {
var displayNameValue = collection[0].getValue();
var subValue = collection[1].getValue();
var html5SourcesValue = collection[2].getValue();
var youtubeValue = collection[3].getValue();
expect(displayNameValue).toEqual('display value');
expect(subValue).toEqual('default');
expect(html5SourcesValue).toEqual([
'video.mp4',
'video.webm'
]);
expect(youtubeValue).toEqual('12345678901');
});
expect(displayNameValue).toEqual('display value');
expect(subValue).toEqual('default');
expect(html5SourcesValue).toEqual([
'video.mp4',
'video.webm'
]);
expect(youtubeValue).toEqual('12345678901');
})
.always(done);
});
it('metadataCollection is not defined', function () {
@@ -307,8 +303,7 @@ function ($, Backbone, _, Utils, Editor, MetadataView, MetadataModel, MetadataCo
transcripts.syncAdvancedTab(metadataCollection);
transcripts.syncAdvancedTab(metadataCollection);
transcripts.syncAdvancedTab(metadataCollection);
expect(subModel.setValue.calls.length).toEqual(1);
expect(subModel.setValue.calls.count()).toEqual(1);
});
});

View File

@@ -2,7 +2,7 @@ define(
[
"jquery", "underscore",
"js/views/video/transcripts/utils", "js/views/video/transcripts/file_uploader",
"xmodule", "jquery.form", "jasmine-jquery"
"xmodule", "jquery.form"
],
function ($, _, Utils, FileUploader) {
// TODO: fix TNL-559 Intermittent failures of Transcript FileUploader JS tests
@@ -43,7 +43,7 @@ function ($, _, Utils, FileUploader) {
.append('<div class="transcripts-file-uploader" />')
.append('<a class="setting-upload" href="#">Upload</a>');
spyOn(FileUploader.prototype, 'render').andCallThrough();
spyOn(FileUploader.prototype, 'render').and.callThrough();
view = new FileUploader({
el: $container,
@@ -61,7 +61,7 @@ function ($, _, Utils, FileUploader) {
describe('Render', function () {
beforeEach(function () {
spyOn(_, 'template').andCallThrough();
spyOn(_, 'template').and.callThrough();
});
it('Template doesn\'t exist', function () {
@@ -138,7 +138,7 @@ function ($, _, Utils, FileUploader) {
});
it('Valid File Type - error should be hided', function () {
spyOn(view, 'checkExtValidity').andReturn(true);
spyOn(view, 'checkExtValidity').and.returnValue(true);
view.$input.change();
@@ -148,7 +148,7 @@ function ($, _, Utils, FileUploader) {
});
it('Invalid File Type - error should be shown', function () {
spyOn(view, 'checkExtValidity').andReturn(false);
spyOn(view, 'checkExtValidity').and.returnValue(false);
view.$input.change();
@@ -189,7 +189,7 @@ function ($, _, Utils, FileUploader) {
it('xhrProgressHandler', function () {
var percent = 26;
spyOn($.fn, 'width').andCallThrough();
spyOn($.fn, 'width').and.callThrough();
view.xhrProgressHandler(null, null, null, percent);
expect(view.$progress.width).toHaveBeenCalledWith(percent + '%');
@@ -209,7 +209,7 @@ function ($, _, Utils, FileUploader) {
view.xhrCompleteHandler(xhr);
expect(view.$progress).toHaveClass('is-invisible');
expect(view.options.messenger.render.mostRecentCall.args[0])
expect(view.options.messenger.render.calls.mostRecent().args[0])
.toEqual('uploaded');
expect(Utils.Storage.set)
.toHaveBeenCalledWith('sub', 'test');

View File

@@ -2,7 +2,7 @@ define(
[
"jquery", "underscore",
"js/views/video/transcripts/utils", "js/views/video/transcripts/message_manager",
"js/views/video/transcripts/file_uploader", "sinon", "jasmine-jquery",
"js/views/video/transcripts/file_uploader", "sinon",
"xmodule"
],
function ($, _, Utils, MessageManager, FileUploader, sinon) {
@@ -67,10 +67,10 @@ function ($, _, Utils, MessageManager, FileUploader, sinon) {
});
// Disabled 2/6/14 after intermittent failure in master
xdescribe('Render', function () {
describe('Render', function () {
beforeEach(function () {
spyOn(_,'template').andCallThrough();
spyOn(_,'template').and.callThrough();
spyOn(fileUploader, 'render');
});
@@ -101,7 +101,7 @@ function ($, _, Utils, MessageManager, FileUploader, sinon) {
beforeEach(function () {
view.render('found');
spyOn(view, 'hideError');
spyOn($.fn, 'html').andCallThrough();
spyOn($.fn, 'html').and.callThrough();
$error = view.$el.find('.transcripts-error-message');
$buttons = view.$el.find('.wrapper-transcripts-buttons');
});
@@ -147,10 +147,10 @@ function ($, _, Utils, MessageManager, FileUploader, sinon) {
$.each(handlers, function(key, value) {
it(key, function () {
var eventObj = jasmine.createSpyObj('event', ['preventDefault']);
spyOn($.fn, 'data').andReturn('video_id');
spyOn($.fn, 'data').and.returnValue('video_id');
spyOn(view, 'processCommand');
view[key](eventObj);
expect(view.processCommand.mostRecentCall.args).toEqual(value);
expect(view.processCommand.calls.mostRecent().args).toEqual(value);
});
});
@@ -162,7 +162,7 @@ function ($, _, Utils, MessageManager, FileUploader, sinon) {
beforeEach(function () {
view.render('found');
spyOn(Utils, 'command').andCallThrough();
spyOn(Utils, 'command').and.callThrough();
spyOn(view, 'render');
spyOn(view, 'showError');
@@ -174,35 +174,19 @@ function ($, _, Utils, MessageManager, FileUploader, sinon) {
sinonXhr.restore();
});
var assertCommand = function (config, expectFunc) {
var flag = false,
defaults = {
var assertCommand = function (config) {
var defaults = {
action: 'replace',
errorMessage: 'errorMessage',
extraParamas: void(0)
};
args = $.extend({}, defaults, config);
var args = $.extend({}, defaults, config);
runs(function() {
view
.processCommand(
args.action,
args.errorMessage,
args.extraParamas
)
.always(function () { flag = true; });
});
waitsFor(function() {
return flag;
}, "Ajax Timeout", 750);
runs(expectFunc);
return view
.processCommand(args.action, args.errorMessage, args.extraParamas);
};
it('Invoke without extraParamas', function () {
it('Invoke without extraParamas', function (done) {
sinonXhr.respondWith([
200,
{ "Content-Type": "application/json"},
@@ -212,9 +196,8 @@ function ($, _, Utils, MessageManager, FileUploader, sinon) {
})
]);
assertCommand(
{ },
function() {
assertCommand({})
.then(function () {
expect(Utils.command).toHaveBeenCalledWith(
action,
view.component_locator,
@@ -222,15 +205,14 @@ function ($, _, Utils, MessageManager, FileUploader, sinon) {
void(0)
);
expect(view.showError).not.toHaveBeenCalled();
expect(view.render.mostRecentCall.args[0])
expect(view.render.calls.mostRecent().args[0])
.toEqual('found');
expect(Utils.Storage.set).toHaveBeenCalled();
}
);
})
.always(done);
});
it('Invoke with extraParamas', function () {
it('Invoke with extraParamas', function (done) {
sinonXhr.respondWith([
200,
{ "Content-Type": "application/json"},
@@ -242,9 +224,8 @@ function ($, _, Utils, MessageManager, FileUploader, sinon) {
view.processCommand(action, errorMessage, extraParamas);
assertCommand(
{ extraParamas : extraParamas },
function () {
assertCommand({extraParamas : extraParamas})
.then(function () {
expect(Utils.command).toHaveBeenCalledWith(
action,
view.component_locator,
@@ -254,20 +235,16 @@ function ($, _, Utils, MessageManager, FileUploader, sinon) {
}
);
expect(view.showError).not.toHaveBeenCalled();
expect(view.render.mostRecentCall.args[0])
.toEqual('found');
expect(view.render.calls.mostRecent().args[0]).toEqual('found');
expect(Utils.Storage.set).toHaveBeenCalled();
}
);
})
.always(done);
});
it('Fail', function () {
it('Fail', function (done) {
sinonXhr.respondWith([400, {}, '']);
assertCommand(
{ },
function () {
assertCommand({})
.then(function () {
expect(Utils.command).toHaveBeenCalledWith(
action,
view.component_locator,
@@ -277,8 +254,8 @@ function ($, _, Utils, MessageManager, FileUploader, sinon) {
expect(view.showError).toHaveBeenCalled();
expect(view.render).not.toHaveBeenCalled();
expect(Utils.Storage.set).not.toHaveBeenCalled();
}
);
})
.always(done);
});
});

View File

@@ -2,7 +2,7 @@ define(
[
'jquery', 'underscore',
'js/views/video/transcripts/utils',
'underscore.string', 'xmodule', 'jasmine-jquery'
'underscore.string', 'xmodule'
],
function ($, _, Utils, _str) {
'use strict';

View File

@@ -5,7 +5,7 @@ define(
'js/views/video/transcripts/metadata_videolist', 'js/models/metadata',
'js/views/abstract_editor',
'common/js/spec_helpers/ajax_helpers',
'xmodule', 'jasmine-jquery'
'xmodule'
],
function ($, _, Utils, VideoList, MetadataModel, AbstractEditor, AjaxHelpers) {
'use strict';
@@ -53,6 +53,19 @@ function ($, _, Utils, VideoList, MetadataModel, AbstractEditor, AjaxHelpers) {
}),
MessageManager, messenger;
var createMockAjaxServer = function () {
var mockServer = AjaxHelpers.server(
[
200,
{ 'Content-Type': 'application/json'},
response
]
);
mockServer.autoRespond = true;
return mockServer;
};
beforeEach(function () {
var tpl = sandbox({
'class': 'component',
@@ -70,9 +83,12 @@ function ($, _, Utils, VideoList, MetadataModel, AbstractEditor, AjaxHelpers) {
).text(videoListEntryTemplate)
);
spyOn(Utils, 'command').andCallThrough();
spyOn(abstractEditor, 'initialize').andCallThrough();
spyOn(abstractEditor, 'render').andCallThrough();
// create mock server
this.mockServer = createMockAjaxServer();
spyOn(Utils, 'command').and.callThrough();
spyOn(abstractEditor, 'initialize').and.callThrough();
spyOn(abstractEditor, 'render').and.callThrough();
spyOn(console, 'error');
messenger = jasmine.createSpyObj('MessageManager',[
@@ -80,7 +96,7 @@ function ($, _, Utils, VideoList, MetadataModel, AbstractEditor, AjaxHelpers) {
]);
$.each(messenger, function(index, method) {
method.andReturn(messenger);
method.and.returnValue(messenger);
});
MessageManager = function () {
@@ -89,40 +105,54 @@ function ($, _, Utils, VideoList, MetadataModel, AbstractEditor, AjaxHelpers) {
return messenger;
};
this.addMatchers({
assertValueInView: function(expected) {
var actualValue = this.actual.getValueFromEditor();
return this.env.equals_(actualValue, expected);
jasmine.addMatchers({
assertValueInView: function() {
return {
compare: function (actual, expected) {
var actualValue = actual.getValueFromEditor(),
passed = _.isEqual(actualValue, expected);
return {
pass: passed
};
}
};
},
assertCanUpdateView: function (expected) {
var actual = this.actual,
actualValue;
assertCanUpdateView: function () {
return {
compare: function (actual, expected) {
var actualValue,
passed;
actual.setValueInEditor(expected);
actualValue = actual.getValueFromEditor();
actual.setValueInEditor(expected);
actualValue = actual.getValueFromEditor();
passed = _.isEqual(actualValue, expected);
return this.env.equals_(actualValue, expected);
return {
pass: passed
};
}
};
},
assertIsCorrectVideoList: function (expected) {
var actualValue = this.actual.getVideoObjectsList();
assertIsCorrectVideoList: function () {
return {
compare: function (actual, expected) {
var actualValue = actual.getVideoObjectsList(),
passed = _.isEqual(actualValue, expected);
return this.env.equals_(actualValue, expected);
return {
pass: passed
};
}
};
}
});
});
var createMockAjaxServer = function (test) {
var mockServer = AjaxHelpers.server(
test,
[
200,
{ 'Content-Type': 'application/json'},
response
]
);
mockServer.autoRespond = true;
return mockServer;
};
afterEach(function () {
// restore mock server
this.mockServer.restore();
});
var createVideoListView = function () {
var model = new MetadataModel(modelStub);
@@ -133,37 +163,25 @@ function ($, _, Utils, VideoList, MetadataModel, AbstractEditor, AjaxHelpers) {
});
};
var waitsForResponse = function (mockServer, expectFunc, prep) {
var flag = false;
if (prep) {
runs(prep);
}
waitsFor(function() {
var waitsForResponse = function (mockServer) {
return jasmine.waitUntil(function () {
var requests = mockServer.requests,
len = requests.length;
if (len && requests[0].readyState === 4) {
flag = true;
}
return flag;
}, 'Ajax Timeout', 750);
runs(expectFunc);
return len && requests[0].readyState === 4;
});
};
it('Initialize', function () {
var mockServer = createMockAjaxServer(this),
view = createVideoListView();
waitsForResponse(mockServer, function () {
expect(abstractEditor.initialize).toHaveBeenCalled();
expect(messenger.initialize).toHaveBeenCalled();
expect(view.component_locator).toBe(component_locator);
expect(view.$el).toHandle('input');
});
it('Initialize', function (done) {
var view = createVideoListView();
waitsForResponse(this.mockServer)
.then(function () {
expect(abstractEditor.initialize).toHaveBeenCalled();
expect(messenger.initialize).toHaveBeenCalled();
expect(view.component_locator).toBe(component_locator);
expect(view.$el).toHandle('input');
}).always(done);
});
describe('Render', function () {
@@ -178,23 +196,23 @@ function ($, _, Utils, VideoList, MetadataModel, AbstractEditor, AjaxHelpers) {
expect(messenger.render).toHaveBeenCalled();
},
resetSpies = function(mockServer) {
abstractEditor.render.reset();
Utils.command.reset();
messenger.render.reset();
abstractEditor.render.calls.reset();
Utils.command.calls.reset();
messenger.render.calls.reset();
mockServer.requests.length = 0;
};
it('is rendered in correct way', function () {
var mockServer = createMockAjaxServer(this);
it('is rendered in correct way', function (done) {
createVideoListView();
waitsForResponse(mockServer, function () {
assertToHaveBeenRendered(videoList);
});
waitsForResponse(this.mockServer)
.then(function () {
assertToHaveBeenRendered(videoList);
})
.always(done);
});
it('is rendered with opened extra videos bar', function () {
var mockServer = createMockAjaxServer(this),
view = createVideoListView();
it('is rendered with opened extra videos bar', function (done) {
var view = createVideoListView();
var videoListLength = [
{
mode: 'youtube',
@@ -215,41 +233,35 @@ function ($, _, Utils, VideoList, MetadataModel, AbstractEditor, AjaxHelpers) {
}
];
spyOn(view, 'getVideoObjectsList').andReturn(videoListLength);
spyOn(view, 'getVideoObjectsList').and.returnValue(videoListLength);
spyOn(view, 'openExtraVideosBar');
waitsForResponse(
mockServer,
function () {
assertToHaveBeenRendered(videoListLength);
view.getVideoObjectsList.andReturn(videoListLength);
expect(view.openExtraVideosBar).toHaveBeenCalled();
},
function () {
resetSpies(mockServer);
view.render();
}
);
resetSpies(this.mockServer);
view.render();
waitsForResponse(
mockServer,
function () {
assertToHaveBeenRendered(videoListHtml5mode);
waitsForResponse(this.mockServer)
.then(function () {
assertToHaveBeenRendered(videoListLength);
view.getVideoObjectsList.and.returnValue(videoListLength);
expect(view.openExtraVideosBar).toHaveBeenCalled();
},
function () {
resetSpies(mockServer);
view.openExtraVideosBar.reset();
view.getVideoObjectsList.andReturn(videoListHtml5mode);
})
.then(_.bind(function () {
resetSpies(this.mockServer);
view.openExtraVideosBar.calls.reset();
view.getVideoObjectsList.and.returnValue(videoListHtml5mode);
view.render();
}
);
return waitsForResponse(this.mockServer)
.then(function () {
assertToHaveBeenRendered(videoListHtml5mode);
expect(view.openExtraVideosBar).toHaveBeenCalled();
}).then(done);
}, this));
});
it('is rendered without opened extra videos bar', function () {
var mockServer = createMockAjaxServer(this),
view = createVideoListView(),
it('is rendered without opened extra videos bar', function (done) {
var view = createVideoListView(),
videoList = [
{
mode: 'youtube',
@@ -258,44 +270,40 @@ function ($, _, Utils, VideoList, MetadataModel, AbstractEditor, AjaxHelpers) {
}
];
spyOn(view, 'getVideoObjectsList').andReturn(videoList);
spyOn(view, 'getVideoObjectsList').and.returnValue(videoList);
spyOn(view, 'closeExtraVideosBar');
waitsForResponse(
mockServer,
function () {
assertToHaveBeenRendered(videoList);
expect(view.closeExtraVideosBar).toHaveBeenCalled();
},
function () {
resetSpies(mockServer);
view.render();
}
);
});
resetSpies(this.mockServer);
view.render();
waitsForResponse(this.mockServer)
.then(function () {
assertToHaveBeenRendered(videoList);
expect(view.closeExtraVideosBar).toHaveBeenCalled();
})
.always(done);
});
});
describe('isUniqOtherVideos', function () {
it('Unique data - return true', function () {
var mockServer = createMockAjaxServer(this),
view = createVideoListView(),
it('Unique data - return true', function (done) {
var view = createVideoListView(),
data = videoList.concat([{
mode: 'html5',
type: 'other',
video: 'pxxZrg'
}]);
waitsForResponse(mockServer, function () {
var result = view.isUniqOtherVideos(data);
expect(result).toBe(true);
});
waitsForResponse(this.mockServer)
.then(function () {
var result = view.isUniqOtherVideos(data);
expect(result).toBe(true);
})
.always(done);
});
it('Not Unique data - return false', function () {
var mockServer = createMockAjaxServer(this),
view = createVideoListView(),
it('Not Unique data - return false', function (done) {
var view = createVideoListView(),
data = [
{
mode: 'html5',
@@ -323,30 +331,31 @@ function ($, _, Utils, VideoList, MetadataModel, AbstractEditor, AjaxHelpers) {
video: '12345678901'
}
];
waitsForResponse(mockServer, function () {
var result = view.isUniqOtherVideos(data);
expect(result).toBe(false);
});
waitsForResponse(this.mockServer)
.then(function () {
var result = view.isUniqOtherVideos(data);
expect(result).toBe(false);
})
.always(done);
});
});
describe('isUniqVideoTypes', function () {
it('Unique data - return true', function () {
var mockServer = createMockAjaxServer(this),
view = createVideoListView(),
it('Unique data - return true', function (done) {
var view = createVideoListView(),
data = videoList;
waitsForResponse(mockServer, function () {
var result = view.isUniqVideoTypes(data);
expect(result).toBe(true);
});
waitsForResponse(this.mockServer)
.then(function () {
var result = view.isUniqVideoTypes(data);
expect(result).toBe(true);
})
.always(done);
});
it('Not Unique data - return false', function () {
var mockServer = createMockAjaxServer(this),
view = createVideoListView(),
it('Not Unique data - return false', function (done) {
var view = createVideoListView(),
data = [
{
mode: 'html5',
@@ -369,18 +378,19 @@ function ($, _, Utils, VideoList, MetadataModel, AbstractEditor, AjaxHelpers) {
video: '12345678901'
}
];
waitsForResponse(mockServer, function () {
var result = view.isUniqVideoTypes(data);
expect(result).toBe(false);
});
waitsForResponse(this.mockServer)
.then(function () {
var result = view.isUniqVideoTypes(data);
expect(result).toBe(false);
})
.always(done);
});
});
describe('checkIsUniqVideoTypes', function () {
it('Error is shown', function () {
var mockServer = createMockAjaxServer(this),
view = createVideoListView(),
it('Error is shown', function (done) {
var view = createVideoListView(),
data = [
{
mode: 'html5',
@@ -404,125 +414,137 @@ function ($, _, Utils, VideoList, MetadataModel, AbstractEditor, AjaxHelpers) {
}
];
waitsForResponse(mockServer, function () {
var result = view.checkIsUniqVideoTypes(data);
waitsForResponse(this.mockServer)
.then(function () {
var result = view.checkIsUniqVideoTypes(data);
expect(messenger.showError).toHaveBeenCalled();
expect(result).toBe(false);
});
expect(messenger.showError).toHaveBeenCalled();
expect(result).toBe(false);
})
.always(done);
});
it('All works okay if arguments are not passed', function () {
var mockServer = createMockAjaxServer(this),
view = createVideoListView();
spyOn(view, 'getVideoObjectsList').andReturn(videoList);
waitsForResponse(mockServer, function () {
var result = view.checkIsUniqVideoTypes();
it('All works okay if arguments are not passed', function (done) {
var view = createVideoListView();
spyOn(view, 'getVideoObjectsList').and.returnValue(videoList);
expect(view.getVideoObjectsList).toHaveBeenCalled();
expect(messenger.showError).not.toHaveBeenCalled();
expect(result).toBe(true);
});
waitsForResponse(this.mockServer)
.then(function () {
var result = view.checkIsUniqVideoTypes();
expect(view.getVideoObjectsList).toHaveBeenCalled();
expect(messenger.showError).not.toHaveBeenCalled();
expect(result).toBe(true);
})
.always(done);
});
});
describe('checkValidity', function () {
it('Error message is shown', function () {
var mockServer = createMockAjaxServer(this),
view = createVideoListView();
spyOn(view, 'checkIsUniqVideoTypes').andReturn(true);
waitsForResponse(mockServer, function () {
var data = { mode: 'incorrect' },
it('Error message is shown', function (done) {
var view = createVideoListView();
spyOn(view, 'checkIsUniqVideoTypes').and.returnValue(true);
waitsForResponse(this.mockServer)
.then(function () {
var data = {mode: 'incorrect'},
result = view.checkValidity(data, true);
expect(messenger.showError).toHaveBeenCalled();
expect(view.checkIsUniqVideoTypes).toHaveBeenCalled();
expect(result).toBe(false);
});
expect(messenger.showError).toHaveBeenCalled();
expect(view.checkIsUniqVideoTypes).toHaveBeenCalled();
expect(result).toBe(false);
})
.always(done);
});
it('Error message is shown when flag is not passed', function () {
var mockServer = createMockAjaxServer(this),
view = createVideoListView();
spyOn(view, 'checkIsUniqVideoTypes').andReturn(true);
waitsForResponse(mockServer, function () {
var data = { mode: 'incorrect' },
it('Error message is shown when flag is not passed', function (done) {
var view = createVideoListView();
spyOn(view, 'checkIsUniqVideoTypes').and.returnValue(true);
waitsForResponse(this.mockServer)
.then(function () {
var data = {mode: 'incorrect'},
result = view.checkValidity(data);
expect(messenger.showError).not.toHaveBeenCalled();
expect(view.checkIsUniqVideoTypes).toHaveBeenCalled();
expect(result).toBe(true);
});
expect(messenger.showError).not.toHaveBeenCalled();
expect(view.checkIsUniqVideoTypes).toHaveBeenCalled();
expect(result).toBe(true);
}).always(done);
});
it('All works okay if correct data is passed', function () {
var mockServer = createMockAjaxServer(this),
view = createVideoListView();
spyOn(view, 'checkIsUniqVideoTypes').andReturn(true);
waitsForResponse(mockServer, function () {
var data = videoList,
it('All works okay if correct data is passed', function (done) {
var view = createVideoListView();
spyOn(view, 'checkIsUniqVideoTypes').and.returnValue(true);
waitsForResponse(this.mockServer)
.then(function () {
var data = videoList,
result = view.checkValidity(data);
expect(messenger.showError).not.toHaveBeenCalled();
expect(view.checkIsUniqVideoTypes).toHaveBeenCalled();
expect(result).toBe(true);
});
expect(messenger.showError).not.toHaveBeenCalled();
expect(view.checkIsUniqVideoTypes).toHaveBeenCalled();
expect(result).toBe(true);
})
.always(done);
});
});
it('openExtraVideosBar', function () {
var mockServer = createMockAjaxServer(this),
view = createVideoListView();
waitsForResponse(mockServer, function () {
view.$extraVideosBar.removeClass('is-visible');
view.openExtraVideosBar();
expect(view.$extraVideosBar).toHaveClass('is-visible');
});
it('openExtraVideosBar', function (done) {
var view = createVideoListView();
waitsForResponse(this.mockServer)
.then(function () {
view.$extraVideosBar.removeClass('is-visible');
view.openExtraVideosBar();
expect(view.$extraVideosBar).toHaveClass('is-visible');
})
.always(done);
});
it('closeExtraVideosBar', function () {
var mockServer = createMockAjaxServer(this),
view = createVideoListView();
waitsForResponse(mockServer, function () {
view.$extraVideosBar.addClass('is-visible');
view.closeExtraVideosBar();
it('closeExtraVideosBar', function (done) {
var view = createVideoListView();
waitsForResponse(this.mockServer)
.then(function () {
view.$extraVideosBar.addClass('is-visible');
view.closeExtraVideosBar();
expect(view.$extraVideosBar).not.toHaveClass('is-visible');
});
expect(view.$extraVideosBar).not.toHaveClass('is-visible');
})
.always(done);
});
it('toggleExtraVideosBar', function () {
var mockServer = createMockAjaxServer(this),
view = createVideoListView();
waitsForResponse(mockServer, function () {
view.$extraVideosBar.addClass('is-visible');
view.toggleExtraVideosBar();
expect(view.$extraVideosBar).not.toHaveClass('is-visible');
view.toggleExtraVideosBar();
expect(view.$extraVideosBar).toHaveClass('is-visible');
});
it('toggleExtraVideosBar', function (done) {
var view = createVideoListView();
waitsForResponse(this.mockServer)
.then(function () {
view.$extraVideosBar.addClass('is-visible');
view.toggleExtraVideosBar();
expect(view.$extraVideosBar).not.toHaveClass('is-visible');
view.toggleExtraVideosBar();
expect(view.$extraVideosBar).toHaveClass('is-visible');
})
.always(done);
});
it('getValueFromEditor', function () {
var mockServer = createMockAjaxServer(this),
view = createVideoListView();
waitsForResponse(mockServer, function () {
expect(view).assertValueInView(modelStub.value);
});
it('getValueFromEditor', function (done) {
var view = createVideoListView();
waitsForResponse(this.mockServer)
.then(function () {
expect(view).assertValueInView(modelStub.value);
})
.always(done);
});
it('setValueInEditor', function () {
var mockServer = createMockAjaxServer(this),
view = createVideoListView();
waitsForResponse(mockServer, function () {
expect(view).assertCanUpdateView(['abc.mp4']);
});
it('setValueInEditor', function (done) {
var view = createVideoListView();
waitsForResponse(this.mockServer)
.then(function () {
expect(view).assertCanUpdateView(['abc.mp4']);
})
.always(done);
});
it('getVideoObjectsList', function () {
var mockServer = createMockAjaxServer(this),
view = createVideoListView();
it('getVideoObjectsList', function (done) {
var view = createVideoListView();
var value = [
{
mode: 'youtube',
@@ -541,36 +563,39 @@ function ($, _, Utils, VideoList, MetadataModel, AbstractEditor, AjaxHelpers) {
}
];
waitsForResponse(mockServer, function () {
view.setValueInEditor([
'http://youtu.be/12345678901',
'video.mp4',
'http://goo.gl/pxxZrg',
'video'
]);
expect(view).assertIsCorrectVideoList(value);
});
waitsForResponse(this.mockServer)
.then(function () {
view.setValueInEditor([
'http://youtu.be/12345678901',
'video.mp4',
'http://goo.gl/pxxZrg',
'video'
]);
expect(view).assertIsCorrectVideoList(value);
})
.always(done);
});
describe('getPlaceholders', function () {
it('All works okay if empty values are passed', function () {
var mockServer = createMockAjaxServer(this),
view = createVideoListView(),
it('All works okay if empty values are passed', function (done) {
var view = createVideoListView(),
defaultPlaceholders = view.placeholders;
waitsForResponse(mockServer, function () {
var result = view.getPlaceholders([]),
expectedResult = _.values(defaultPlaceholders).reverse();
expect(result).toEqual(expectedResult);
});
waitsForResponse(this.mockServer)
.then(function () {
var result = view.getPlaceholders([]),
expectedResult = _.values(defaultPlaceholders).reverse();
expect(result).toEqual(expectedResult);
})
.always(done);
});
it('On filling less than 3 fields, remaining fields should have ' +
'placeholders for video types that were not filled yet',
function () {
var mockServer = createMockAjaxServer(this),
view = createVideoListView(),
function (done) {
var view = createVideoListView(),
defaultPlaceholders = view.placeholders;
var dataDict = {
youtube: {
@@ -598,14 +623,17 @@ function ($, _, Utils, VideoList, MetadataModel, AbstractEditor, AjaxHelpers) {
]
}
};
defaultPlaceholders = view.placeholders;
waitsForResponse(mockServer, function () {
$.each(dataDict, function(index, val) {
var result = view.getPlaceholders(val.value);
expect(result).toEqual(val.expectedResult);
});
});
defaultPlaceholders = view.placeholders;
waitsForResponse(this.mockServer)
.then(function () {
$.each(dataDict, function (index, val) {
var result = view.getPlaceholders(val.value);
expect(result).toEqual(val.expectedResult);
});
})
.always(done);
}
);
});
@@ -614,9 +642,9 @@ function ($, _, Utils, VideoList, MetadataModel, AbstractEditor, AjaxHelpers) {
var eventObject;
var resetSpies = function (view) {
messenger.hideError.reset();
view.updateModel.reset();
view.closeExtraVideosBar.reset();
messenger.hideError.calls.reset();
view.updateModel.calls.reset();
view.closeExtraVideosBar.calls.reset();
};
var setUp = function (view) {
@@ -628,100 +656,104 @@ function ($, _, Utils, VideoList, MetadataModel, AbstractEditor, AjaxHelpers) {
spyOn($.fn, 'hasClass');
spyOn($.fn, 'addClass');
spyOn($.fn, 'removeClass');
spyOn($.fn, 'prop').andCallThrough();
spyOn($.fn, 'prop').and.callThrough();
spyOn(_, 'isEqual');
resetSpies(view);
};
it('Field has invalid value - nothing should happen',
function () {
var mockServer = createMockAjaxServer(this),
view = createVideoListView();
function (done) {
var view = createVideoListView();
setUp(view);
$.fn.hasClass.andReturn(false);
view.checkValidity.andReturn(false);
$.fn.hasClass.and.returnValue(false);
view.checkValidity.and.returnValue(false);
waitsForResponse(mockServer, function () {
view.inputHandler(eventObject);
expect(messenger.hideError).not.toHaveBeenCalled();
expect(view.updateModel).not.toHaveBeenCalled();
expect(view.closeExtraVideosBar).not.toHaveBeenCalled();
expect($.fn.prop).toHaveBeenCalledWith(
'disabled', true
);
expect($.fn.addClass).toHaveBeenCalledWith(
'is-disabled'
);
});
waitsForResponse(this.mockServer)
.then(function () {
view.inputHandler(eventObject);
expect(messenger.hideError).not.toHaveBeenCalled();
expect(view.updateModel).not.toHaveBeenCalled();
expect(view.closeExtraVideosBar).not.toHaveBeenCalled();
expect($.fn.prop).toHaveBeenCalledWith(
'disabled', true
);
expect($.fn.addClass).toHaveBeenCalledWith(
'is-disabled'
);
})
.always(done);
}
);
it('Main field has invalid value - extra Videos Bar is closed',
function () {
var mockServer = createMockAjaxServer(this),
view = createVideoListView();
function (done) {
var view = createVideoListView();
setUp(view);
$.fn.hasClass.andReturn(true);
view.checkValidity.andReturn(false);
$.fn.hasClass.and.returnValue(true);
view.checkValidity.and.returnValue(false);
waitsForResponse(mockServer, function () {
view.inputHandler(eventObject);
expect(messenger.hideError).not.toHaveBeenCalled();
expect(view.updateModel).not.toHaveBeenCalled();
expect(view.closeExtraVideosBar).toHaveBeenCalled();
expect($.fn.prop).toHaveBeenCalledWith(
'disabled', true
);
expect($.fn.addClass).toHaveBeenCalledWith(
'is-disabled'
);
});
waitsForResponse(this.mockServer)
.then(function () {
view.inputHandler(eventObject);
expect(messenger.hideError).not.toHaveBeenCalled();
expect(view.updateModel).not.toHaveBeenCalled();
expect(view.closeExtraVideosBar).toHaveBeenCalled();
expect($.fn.prop).toHaveBeenCalledWith(
'disabled', true
);
expect($.fn.addClass).toHaveBeenCalledWith(
'is-disabled'
);
})
.always(done);
}
);
it('Model is updated if value is valid',
function () {
var mockServer = createMockAjaxServer(this),
view = createVideoListView();
function (done) {
var view = createVideoListView();
setUp(view);
view.checkValidity.andReturn(true);
_.isEqual.andReturn(false);
view.checkValidity.and.returnValue(true);
_.isEqual.and.returnValue(false);
waitsForResponse(mockServer, function () {
view.inputHandler(eventObject);
expect(messenger.hideError).not.toHaveBeenCalled();
expect(view.updateModel).toHaveBeenCalled();
expect(view.closeExtraVideosBar).not.toHaveBeenCalled();
expect($.fn.prop).toHaveBeenCalledWith(
'disabled', false
);
expect($.fn.removeClass).toHaveBeenCalledWith(
'is-disabled'
);
});
waitsForResponse(this.mockServer)
.then(function () {
view.inputHandler(eventObject);
expect(messenger.hideError).not.toHaveBeenCalled();
expect(view.updateModel).toHaveBeenCalled();
expect(view.closeExtraVideosBar).not.toHaveBeenCalled();
expect($.fn.prop).toHaveBeenCalledWith(
'disabled', false
);
expect($.fn.removeClass).toHaveBeenCalledWith(
'is-disabled'
);
})
.always(done);
}
);
it('Corner case: Error is hided',
function () {
var mockServer = createMockAjaxServer(this),
view = createVideoListView();
function (done) {
var view = createVideoListView();
setUp(view);
view.checkValidity.andReturn(true);
_.isEqual.andReturn(true);
waitsForResponse(mockServer, function () {
view.inputHandler(eventObject);
expect(messenger.hideError).toHaveBeenCalled();
expect(view.updateModel).not.toHaveBeenCalled();
expect(view.closeExtraVideosBar).not.toHaveBeenCalled();
expect($.fn.prop).toHaveBeenCalledWith(
'disabled', false
);
expect($.fn.removeClass).toHaveBeenCalledWith(
'is-disabled'
);
});
view.checkValidity.and.returnValue(true);
_.isEqual.and.returnValue(true);
waitsForResponse(this.mockServer)
.then(function () {
view.inputHandler(eventObject);
expect(messenger.hideError).toHaveBeenCalled();
expect(view.updateModel).not.toHaveBeenCalled();
expect(view.closeExtraVideosBar).not.toHaveBeenCalled();
expect($.fn.prop).toHaveBeenCalledWith(
'disabled', false
);
expect($.fn.removeClass).toHaveBeenCalledWith(
'is-disabled'
);
})
.always(done);
}
);

View File

@@ -45,82 +45,133 @@ function ($, _, Squire) {
var createPromptSpy = function (name) {
var spy = jasmine.createSpyObj(name, ['constructor', 'show', 'hide']);
spy.constructor.andReturn(spy);
spy.show.andReturn(spy);
spy.extend = jasmine.createSpy().andReturn(spy.constructor);
spy.constructor.and.returnValue(spy);
spy.show.and.returnValue(spy);
spy.extend = jasmine.createSpy().and.returnValue(spy.constructor);
return spy;
};
beforeEach(function () {
beforeEach(function (done) {
self = this;
this.addMatchers({
assertValueInView: function(expected) {
var value = this.actual.getValueFromEditor();
return this.env.equals_(value, expected);
jasmine.addMatchers({
assertValueInView: function() {
return {
compare: function (actual, expected) {
var value = actual.getValueFromEditor();
var passed = _.isEqual(value, expected);
return {
pass: passed,
message: 'Expected ' + actual + (passed ? '' : ' not') + ' to equal ' + expected
};
}
};
},
assertCanUpdateView: function (expected) {
var view = this.actual,
value;
assertCanUpdateView: function () {
return {
compare: function (actual, expected) {
var view = actual,
value,
passed;
view.setValueInEditor(expected);
value = view.getValueFromEditor();
view.setValueInEditor(expected);
value = view.getValueFromEditor();
passed = _.isEqual(value, expected);
return this.env.equals_(value, expected);
return {
pass: passed,
message: 'Expected ' + actual + (passed ? '' : ' not') + ' to equal ' + expected
};
}
};
},
assertClear: function (modelValue) {
var env = this.env,
view = this.actual,
model = view.model;
assertClear: function () {
return {
compare: function (actual, modelValue) {
var view = actual,
model = view.model,
passed;
return model.getValue() === null &&
env.equals_(model.getDisplayValue(), modelValue) &&
env.equals_(view.getValueFromEditor(), modelValue);
passed = model.getValue() === null &&
_.isEqual(model.getDisplayValue(), modelValue) &&
_.isEqual(view.getValueFromEditor(), modelValue);
return {
pass: passed
};
}
};
},
assertUpdateModel: function (originalValue, newValue) {
var env = this.env,
view = this.actual,
model = view.model,
expectOriginal;
assertUpdateModel: function () {
return {
compare: function (actual, originalValue, newValue) {
var view = actual,
model = view.model,
expectOriginal,
passed;
view.setValueInEditor(newValue);
expectOriginal = env.equals_(model.getValue(), originalValue);
view.updateModel();
view.setValueInEditor(newValue);
expectOriginal = _.isEqual(model.getValue(), originalValue);
view.updateModel();
return expectOriginal &&
env.equals_(model.getValue(), newValue);
passed = expectOriginal &&
_.isEqual(model.getValue(), newValue);
return {
pass: passed
};
}
};
},
verifyKeysUnique: function (initial, expected, testData) {
var env = this.env,
view = this.actual,
item, value;
verifyKeysUnique: function () {
return {
compare: function (actual, initial, expected, testData) {
var view = this.actual,
item,
value,
passed;
view.setValueInEditor(initial);
view.updateModel();
view.$el.find('.create-setting').click();
item = view.$el.find('.list-settings-item').last();
item.find('select').val(testData.key);
item.find('input:hidden').val(testData.value);
value = view.getValueFromEditor();
view.setValueInEditor(initial);
view.updateModel();
view.$el.find('.create-setting').click();
item = view.$el.find('.list-settings-item').last();
item.find('select').val(testData.key);
item.find('input:hidden').val(testData.value);
value = view.getValueFromEditor();
return env.equals_(value, expected);
passed = _.isEqual(value, expected);
return {
pass: passed
};
}
};
},
verifyButtons: function (upload, download, remove, index) {
var view = this.actual,
items = view.$el.find('.list-settings-item'),
item = index ? items.eq(index) : items.last(),
uploadBtn = item.find('.upload-setting'),
downloadBtn = item.find('.download-setting'),
removeBtn = item.find('.remove-setting');
verifyButtons: function () {
return {
compare: function (actual, upload, download, remove, index) {
var view = this.actual,
items = view.$el.find('.list-settings-item'),
item = index ? items.eq(index) : items.last(),
uploadBtn = item.find('.upload-setting'),
downloadBtn = item.find('.download-setting'),
removeBtn = item.find('.remove-setting'),
passed;
upload = upload ? uploadBtn.length : !uploadBtn.length;
download = download ? downloadBtn.length : !downloadBtn.length;
remove = remove ? removeBtn.length : !removeBtn.length;
upload = upload ? uploadBtn.length : !uploadBtn.length;
download = download ? downloadBtn.length : !downloadBtn.length;
remove = remove ? removeBtn.length : !removeBtn.length;
return upload && download && remove;
passed = upload && download && remove;
return {
pass: passed
};
}
};
}
});
@@ -141,19 +192,15 @@ function ($, _, Squire) {
return self.uploadSpies;
});
runs(function() {
injector.require([
injector.require([
'js/models/metadata', 'js/views/video/translations_editor'
],
function(MetadataModel, Translations) {
function (MetadataModel, Translations) {
var model = new MetadataModel($.extend(true, {}, modelStub));
self.view = new Translations({model: model});
});
});
waitsFor(function() {
return self.view;
}, 'VideoTranslations was not created', 1000);
done();
});
});
afterEach(function () {
@@ -198,7 +245,7 @@ function ($, _, Squire) {
expect(this.uploadSpies.constructor).toHaveBeenCalled();
expect(this.uploadSpies.show).toHaveBeenCalled();
options = this.uploadSpies.constructor.mostRecentCall.args[0];
options = this.uploadSpies.constructor.calls.mostRecent().args[0];
options.onSuccess({'filename': 'zh.srt'});
expect(this.view).verifyButtons(true, true, true);

View File

@@ -1,5 +1,11 @@
define(
["jquery", "js/models/active_video_upload", "js/views/active_video_upload_list", "common/js/spec_helpers/template_helpers", "mock-ajax", "jasmine-jquery"],
[
"jquery",
"js/models/active_video_upload",
"js/views/active_video_upload_list",
"common/js/spec_helpers/template_helpers",
"mock-ajax"
],
function($, ActiveVideoUpload, ActiveVideoUploadListView, TemplateHelpers) {
"use strict";
var concurrentUploadLimit = 2;
@@ -16,8 +22,7 @@ define(
uploadButton: this.uploadButton
});
this.view.render();
jasmine.Ajax.useMock();
clearAjaxRequests();
jasmine.Ajax.install();
this.globalAjaxError = jasmine.createSpy();
$(document).ajaxError(this.globalAjaxError);
});
@@ -25,15 +30,16 @@ define(
// Remove window unload handler triggered by the upload requests
afterEach(function() {
$(window).off("beforeunload");
jasmine.Ajax.uninstall();
});
it("should trigger file selection when either the upload button or the drop zone is clicked", function() {
var clickSpy = jasmine.createSpy();
clickSpy.andCallFake(function(event) { event.preventDefault(); });
clickSpy.and.callFake(function(event) { event.preventDefault(); });
this.view.$(".js-file-input").on("click", clickSpy);
this.view.$(".file-drop-area").click();
expect(clickSpy).toHaveBeenCalled();
clickSpy.reset();
clickSpy.calls.reset();
this.uploadButton.click();
expect(clickSpy).toHaveBeenCalled();
});
@@ -47,17 +53,16 @@ define(
};
var getSentRequests = function() {
return _.filter(
ajaxRequests,
function(request) { return request.readyState > 0; }
);
return jasmine.Ajax.requests.filter(function (request) {
return request.readyState > 0;
});
};
_.each(
[
{desc: "a single file", numFiles: 1},
{desc: "multiple files", numFiles: concurrentUploadLimit},
{desc: "more files than upload limit", numFiles: concurrentUploadLimit + 1},
{desc: "more files than upload limit", numFiles: concurrentUploadLimit + 1}
],
function(caseInfo) {
var fileNames = _.map(
@@ -71,7 +76,7 @@ define(
// security reasons, so we must mock the access mechanism
// that jQuery-File-Upload uses to retrieve it.
var realProp = $.prop;
spyOn($, "prop").andCallFake(function(el, propName) {
spyOn($, "prop").and.callFake(function(el, propName) {
if (arguments.length == 2 && propName == "files") {
return _.map(
fileNames,
@@ -82,7 +87,7 @@ define(
}
});
this.view.$(".js-file-input").change();
this.request = mostRecentAjaxRequest();
this.request = jasmine.Ajax.requests.mostRecent();
});
it("should trigger the correct request", function() {
@@ -99,14 +104,14 @@ define(
});
it("should trigger the global AJAX error handler on server error", function() {
this.request.response({status: 500});
this.request.respondWith({status: 500});
expect(this.globalAjaxError).toHaveBeenCalled();
});
describe("and successful server response", function() {
beforeEach(function() {
clearAjaxRequests();
this.request.response({
jasmine.Ajax.requests.reset();
this.request.respondWith({
status: 200,
responseText: JSON.stringify({
files: _.map(
@@ -141,7 +146,6 @@ define(
});
it("should display upload status and progress", function() {
var spec = this;
expect(this.$uploadElems.length).toEqual(caseInfo.numFiles);
this.$uploadElems.each(function(i, uploadElem) {
var $uploadElem = $(uploadElem);
@@ -154,7 +158,7 @@ define(
ActiveVideoUpload.STATUS_QUEUED :
ActiveVideoUpload.STATUS_UPLOADING
);
expect($uploadElem.find(".video-detail-progress").attr("value")).toEqual(0);
expect($uploadElem.find(".video-detail-progress").val()).toEqual(0);
expect($uploadElem).not.toHaveClass("success");
expect($uploadElem).not.toHaveClass("error");
expect($uploadElem.hasClass("queued")).toEqual(queued);
@@ -187,12 +191,12 @@ define(
progressValue: 0,
presentClass: "error",
absentClass: "success"
},
}
],
function(subCaseInfo) {
describe("and upload " + subCaseInfo.desc, function() {
beforeEach(function() {
getSentRequests()[0].response({status: subCaseInfo.responseStatus});
getSentRequests()[0].respondWith({status: subCaseInfo.responseStatus});
});
it("should update status and progress", function() {
@@ -202,7 +206,7 @@ define(
subCaseInfo.statusText
);
expect(
$uploadElem.find(".video-detail-progress").attr("value")
$uploadElem.find(".video-detail-progress").val()
).toEqual(subCaseInfo.progressValue);
expect($uploadElem).toHaveClass(subCaseInfo.presentClass);
expect($uploadElem).not.toHaveClass(subCaseInfo.absentClass);

View File

@@ -16,7 +16,7 @@ define([ "jquery", "common/js/spec_helpers/ajax_helpers", "URI", "js/views/asset
appendSetFixtures(uploadModalTpl);
appendSetFixtures(sandbox({ id: "asset_table_body" }));
spyOn($.fn, "fileupload").andReturn("");
spyOn($.fn, "fileupload").and.returnValue("");
var collection = new AssetCollection();
collection.url = "assets-url";
@@ -181,7 +181,7 @@ define([ "jquery", "common/js/spec_helpers/ajax_helpers", "URI", "js/views/asset
it('uploads file properly', function () {
var requests = setup.call(this);
expect(assetsView).toBeDefined();
spyOn(assetsView, "addAsset").andCallFake(function () {
spyOn(assetsView, "addAsset").and.callFake(function () {
assetsView.collection.add(mockAssetUploadResponse.asset);
assetsView.pagingView.renderPageItems();
assetsView.pagingView.setPage(0);

View File

@@ -13,8 +13,8 @@ define(["jquery", "underscore", "js/views/baseview", "js/utils/handle_iframe_bin
spyOn(baseViewPrototype, 'initialize');
spyOn(baseViewPrototype, 'beforeRender');
spyOn(baseViewPrototype, 'render').andCallThrough();
spyOn(baseViewPrototype, 'afterRender').andCallThrough();
spyOn(baseViewPrototype, 'render').and.callThrough();
spyOn(baseViewPrototype, 'afterRender').and.callThrough();
});
afterEach(function () {

View File

@@ -125,7 +125,7 @@ define([
ViewHelpers.verifyNotificationShowing(notificationSpy, /Deleting/);
expect($(listItemView)).toExist();
};
var assertCannotDeleteUsed = function (that, toolTipText, warningText){
var assertCannotDeleteUsed = function (that, toolTipText, warningText) {
setUsageInfo(that.model);
that.view.render();
expect(that.view.$(SELECTORS.note)).toHaveAttr(
@@ -153,36 +153,69 @@ define([
revision: 'course_rev'
});
this.addMatchers({
toContainText: function(text) {
var trimmedText = $.trim(this.actual.text());
jasmine.addMatchers({
toContainText: function() {
return {
compare: function (actual, text) {
var trimmedText = $.trim(actual.text()),
passed;
if (text && $.isFunction(text.test)) {
return text.test(trimmedText);
} else {
return trimmedText.indexOf(text) !== -1;
}
},
toBeCorrectValuesInInputs: function (values) {
var expected = {
name: this.actual.$(SELECTORS.inputName).val(),
description: this.actual
.$(SELECTORS.inputDescription).val()
if (text && $.isFunction(text.test)) {
passed = text.test(trimmedText);
} else {
passed = trimmedText.indexOf(text) !== -1;
}
return {
pass: passed
};
}
};
return _.isEqual(values, expected);
},
toBeCorrectValuesInModel: function (values) {
return _.every(values, function (value, key) {
return this.actual.get(key) === value;
}.bind(this));
},
toHaveDefaultNames: function (values) {
var actualValues = $.map(this.actual, function (item) {
return $(item).val();
});
toBeCorrectValuesInInputs: function () {
return {
compare: function (actual, values) {
var expected = {
name: actual.$(SELECTORS.inputName).val(),
description: actual
.$(SELECTORS.inputDescription).val()
};
return _.isEqual(actualValues, values);
var passed = _.isEqual(values, expected);
return {
pass: passed
};
}
};
},
toBeCorrectValuesInModel: function () {
return {
compare: function (actual, values) {
var passed = _.every(values, function (value, key) {
return actual.get(key) === value;
}.bind(this));
return {
pass: passed
};
}
};
},
toHaveDefaultNames: function () {
return {
compare: function (actual, values) {
var actualValues = $.map(actual, function (item) {
return $(item).val();
});
var passed = _.isEqual(actualValues, values);
return {
pass: passed
};
}
};
}
});
});
@@ -389,7 +422,7 @@ define([
groups = this.model.get('groups');
expect(groups.length).toBe(3);
expect(groups.at(2).get('name')).toBe('Group C');
expect(this.view.$el).not.toExist();
expect(this.view.$el).not.toBeInDOM();
});
it('does not hide saving message if failure', function() {
@@ -421,7 +454,7 @@ define([
});
it('should be removed on cancel if it is a new item', function() {
spyOn(this.model, 'isNew').andReturn(true);
spyOn(this.model, 'isNew').and.returnValue(true);
setValuesToInputs(this.view, {
inputName: 'New Configuration',
inputDescription: 'New Description'
@@ -454,18 +487,23 @@ define([
name: 'New Configuration'
});
// Error message disappear
expect(this.view.$(SELECTORS.errorMessage)).not.toExist();
expect(this.view.$(SELECTORS.errorMessage)).not.toBeInDOM();
AjaxHelpers.expectNoRequests(requests);
});
it('should have appropriate class names on focus/blur', function () {
it('should have appropriate class names on focus/blur', function (done) {
var groupInput = this.view.$(SELECTORS.inputGroupName).first(),
groupFields = this.view.$(SELECTORS.groupFields);
groupInput.focus();
expect(groupFields).toHaveClass('is-focused');
groupInput.blur();
expect(groupFields).not.toHaveClass('is-focused');
jasmine.waitUntil(function() {
return groupFields.hasClass('is-focused');
}).then(function () {
groupInput.blur();
jasmine.waitUntil(function() {
return !groupFields.hasClass('is-focused');
}).then(done);
});
});
describe('removes all newly created groups on cancel', function () {
@@ -957,13 +995,13 @@ define([
expect(this.model).toBeCorrectValuesInModel({
name: 'New Content Group'
});
expect(this.view.$el).not.toExist();
expect(this.view.$el).not.toBeInDOM();
});
it('does not hide saving message if failure', function() {
var requests = AjaxHelpers.requests(this),
notificationSpy = ViewHelpers.createNotificationSpy();
this.view.$(SELECTORS.inputName).val('New Content Group')
this.view.$(SELECTORS.inputName).val('New Content Group');
ViewHelpers.submitAndVerifyFormError(this.view, requests, notificationSpy)
});

View File

@@ -12,7 +12,7 @@ function($, LoginFactory, AjaxHelpers, ViewUtils) {
});
it('disable the submit button once it is clicked', function() {
spyOn(ViewUtils, 'redirect').andCallFake(function(){});
spyOn(ViewUtils, 'redirect').and.callFake(function(){});
var requests = AjaxHelpers.requests(this);
expect(submitButton).not.toHaveClass('is-disabled');
submitButton.click();

View File

@@ -31,14 +31,13 @@ define(["jquery", "underscore", "js/views/modals/base_modal", "js/spec_helpers/m
expect(ModelHelpers.isShowingModal(modal)).toBeTruthy();
});
it('sends focus to the modal window after show is called', function() {
it('sends focus to the modal window after show is called', function(done) {
showMockModal();
waitsFor(function () {
// This is the implementation of "toBeFocused". However, simply calling that method
// with no wait seems to be flaky.
jasmine.waitUntil(function() {
var modalWindow = ModelHelpers.getModalWindow(modal);
return $(modalWindow)[0] === $(modalWindow)[0].ownerDocument.activeElement;
}, 'Modal Window did not get focus', 5000);
return ($(modalWindow)[0] === $(modalWindow)[0].ownerDocument.activeElement);
}).then(done);
});
it('is removed after hide is called', function () {

View File

@@ -51,7 +51,7 @@ define(['jquery', 'underscore', 'js/spec_helpers/validation_helpers', 'js/views/
ValidationHelpers.checkErrorContents(modal, errorObjects);
});
it('run callback when undo changes button is clicked', function () {
it('run callback when undo changes button is clicked', function (done) {
var errorObjects = [
{
model: {display_name: 'test_attribute1'},
@@ -64,7 +64,7 @@ define(['jquery', 'underscore', 'js/spec_helpers/validation_helpers', 'js/views/
];
var callback = function() {
return true;
done();
};
// Show Modal and click undo changes
@@ -72,15 +72,8 @@ define(['jquery', 'underscore', 'js/spec_helpers/validation_helpers', 'js/views/
expect(ValidationHelpers.isShowingModal(modal)).toBeTruthy();
ValidationHelpers.undoChanges(modal);
// Wait for the callback to be fired
waitsFor(function () {
return callback();
}, 'the callback to be called', 5000);
// After checking callback fire, check modal hide
runs(function () {
expect(ValidationHelpers.isShowingModal(modal)).toBe(false);
});
expect(ValidationHelpers.isShowingModal(modal)).toBe(false);
});
});
});

View File

@@ -74,7 +74,10 @@ define(["jquery", "underscore", "common/js/spec_helpers/ajax_helpers", "URI", "j
var pagingContainer;
beforeEach(function () {
pagingContainer = new MockPagingView({page_size: PAGE_SIZE});
pagingContainer = new MockPagingView({
page_size: PAGE_SIZE,
page: jasmine.createSpyObj('page', ['updatePreviewButton', 'renderAddXBlockComponents'])
});
});
describe("Container", function () {
@@ -546,7 +549,7 @@ define(["jquery", "underscore", "common/js/spec_helpers/ajax_helpers", "URI", "j
mockXBlockView.model.id = 'mock-location';
pagingContainer.refresh(mockXBlockView, true);
expect(pagingContainer.render).toHaveBeenCalled();
expect(pagingContainer.render.mostRecentCall.args[0].force_render).toEqual('mock-location');
expect(pagingContainer.render.calls.mostRecent().args[0].force_render).toEqual('mock-location');
});
});
});

View File

@@ -70,7 +70,7 @@ define(["jquery", "underscore", "underscore.string", "common/js/spec_helpers/aja
containerPage.render();
respondWithHtml(html);
AjaxHelpers.expectJsonRequest(requests, 'GET', '/xblock/locator-container');
AjaxHelpers.respondWithJson(requests, options);
AjaxHelpers.respondWithJson(requests, options || {});
};
handleContainerPageRefresh = function(requests) {

View File

@@ -1,9 +1,10 @@
define(["jquery", "underscore", "underscore.string", "common/js/spec_helpers/ajax_helpers",
"common/js/spec_helpers/template_helpers", "js/spec_helpers/edit_helpers",
"common/js/components/views/feedback_prompt", "js/views/pages/container",
"js/views/pages/container_subviews", "js/models/xblock_info", "js/views/utils/xblock_utils"],
"js/views/pages/container_subviews", "js/models/xblock_info", "js/views/utils/xblock_utils",
'js/models/course'],
function ($, _, str, AjaxHelpers, TemplateHelpers, EditHelpers, Prompt, ContainerPage, ContainerSubviews,
XBlockInfo, XBlockUtils) {
XBlockInfo, XBlockUtils, Course) {
var VisibilityState = XBlockUtils.VisibilityState;
describe("Container Subviews", function() {
@@ -14,12 +15,26 @@ define(["jquery", "underscore", "underscore.string", "common/js/spec_helpers/aja
mockContainerXBlockHtml = readFixtures('mock/mock-empty-container-xblock.underscore');
beforeEach(function () {
window.course = new Course({
id: '5',
name: 'Course Name',
url_name: 'course_name',
org: 'course_org',
num: 'course_num',
revision: 'course_rev'
});
TemplateHelpers.installTemplate('xblock-string-field-editor');
TemplateHelpers.installTemplate('publish-xblock');
TemplateHelpers.installTemplate('publish-history');
TemplateHelpers.installTemplate('unit-outline');
TemplateHelpers.installTemplate('container-message');
appendSetFixtures(mockContainerPage);
requests = AjaxHelpers.requests(this);
});
afterEach(function() {
delete window.course;
});
defaultXBlockInfo = {
@@ -39,7 +54,6 @@ define(["jquery", "underscore", "underscore.string", "common/js/spec_helpers/aja
};
createContainerPage = function (test, options) {
requests = AjaxHelpers.requests(test);
model = new XBlockInfo(createXBlockInfo(options), { parse: true });
containerPage = new ContainerPage({
model: model,
@@ -135,7 +149,7 @@ define(["jquery", "underscore", "underscore.string", "common/js/spec_helpers/aja
// Confirm the discard.
expect(promptSpies.constructor).toHaveBeenCalled();
promptSpies.constructor.mostRecentCall.args[0].actions.primary.click(promptSpies);
promptSpies.constructor.calls.mostRecent().args[0].actions.primary.click(promptSpies);
AjaxHelpers.expectJsonRequest(requests, "POST", "/xblock/locator-container",
{"publish": "discard_changes"}
@@ -152,8 +166,8 @@ define(["jquery", "underscore", "underscore.string", "common/js/spec_helpers/aja
};
beforeEach(function() {
promptSpies = spyOnConstructor(Prompt, "Warning", ["show", "hide"]);
promptSpies.show.andReturn(this.promptSpies);
promptSpies = jasmine.stealth.spyOnConstructor(Prompt, "Warning", ["show", "hide"]);
promptSpies.show.and.returnValue(this.promptSpies);
});
it('renders correctly with private content', function () {
@@ -268,7 +282,7 @@ define(["jquery", "underscore", "underscore.string", "common/js/spec_helpers/aja
var notificationSpy, renderPageSpy, numRequests;
createContainerPage(this);
notificationSpy = EditHelpers.createNotificationSpy();
renderPageSpy = spyOn(containerPage.xblockPublisher, 'renderPage').andCallThrough();
renderPageSpy = spyOn(containerPage.xblockPublisher, 'renderPage').and.callThrough();
sendDiscardChangesToServer();
numRequests = requests.length;
@@ -287,7 +301,7 @@ define(["jquery", "underscore", "underscore.string", "common/js/spec_helpers/aja
it('does not fetch if discard changes fails', function () {
var renderPageSpy, numRequests;
createContainerPage(this);
renderPageSpy = spyOn(containerPage.xblockPublisher, 'renderPage').andCallThrough();
renderPageSpy = spyOn(containerPage.xblockPublisher, 'renderPage').and.callThrough();
sendDiscardChangesToServer();
@@ -309,7 +323,7 @@ define(["jquery", "underscore", "underscore.string", "common/js/spec_helpers/aja
// Click cancel to confirmation.
expect(promptSpies.constructor).toHaveBeenCalled();
promptSpies.constructor.mostRecentCall.args[0].actions.secondary.click(promptSpies);
promptSpies.constructor.calls.mostRecent().args[0].actions.secondary.click(promptSpies);
AjaxHelpers.expectNoRequests(requests);
expect(containerPage.$(discardChangesButtonCss)).not.toHaveClass('is-disabled');
});

View File

@@ -1,14 +1,15 @@
define(["jquery", "common/js/spec_helpers/ajax_helpers", "common/js/components/utils/view_utils", "js/views/pages/course_outline",
"js/models/xblock_outline_info", "js/utils/date_utils", "js/spec_helpers/edit_helpers",
"common/js/spec_helpers/template_helpers"],
function($, AjaxHelpers, ViewUtils, CourseOutlinePage, XBlockOutlineInfo, DateUtils, EditHelpers, TemplateHelpers) {
"common/js/spec_helpers/template_helpers", 'js/models/course',],
function($, AjaxHelpers, ViewUtils, CourseOutlinePage, XBlockOutlineInfo, DateUtils,
EditHelpers, TemplateHelpers, Course) {
describe("CourseOutlinePage", function() {
var createCourseOutlinePage, displayNameInput, model, outlinePage, requests,
getItemsOfType, getItemHeaders, verifyItemsExpanded, expandItemsAndVerifyState,
collapseItemsAndVerifyState, createMockCourseJSON, createMockSectionJSON, createMockSubsectionJSON,
verifyTypePublishable, mockCourseJSON, mockEmptyCourseJSON, mockSingleSectionCourseJSON,
createMockVerticalJSON, createMockIndexJSON, mockCourseEntranceExamJSON
createMockVerticalJSON, createMockIndexJSON, mockCourseEntranceExamJSON,
mockOutlinePage = readFixtures('mock/mock-course-outline-page.underscore'),
mockRerunNotification = readFixtures('mock/mock-course-rerun-notification.underscore');
@@ -214,6 +215,15 @@ define(["jquery", "common/js/spec_helpers/ajax_helpers", "common/js/components/u
};
beforeEach(function () {
window.course = new Course({
id: '5',
name: 'Course Name',
url_name: 'course_name',
org: 'course_org',
num: 'course_num',
revision: 'course_rev'
});
EditHelpers.installMockAnalytics();
EditHelpers.installViewTemplates();
TemplateHelpers.installTemplates([
@@ -252,6 +262,7 @@ define(["jquery", "common/js/spec_helpers/ajax_helpers", "common/js/components/u
$("#start_date").datepicker( "destroy" );
$("#due_date").datepicker( "destroy" );
$('.ui-datepicker').remove();
delete window.course;
});
describe('Initial display', function() {
@@ -346,8 +357,8 @@ define(["jquery", "common/js/spec_helpers/ajax_helpers", "common/js/components/u
it('can start reindex of a course', function() {
createCourseOutlinePage(this, mockSingleSectionCourseJSON);
var reindexSpy = spyOn(outlinePage, 'startReIndex').andCallThrough();
var successSpy = spyOn(outlinePage, 'onIndexSuccess').andCallThrough();
var reindexSpy = spyOn(outlinePage, 'startReIndex').and.callThrough();
var successSpy = spyOn(outlinePage, 'onIndexSuccess').and.callThrough();
var reindexButton = outlinePage.$('.button.button-reindex');
var test_url = '/course/5/search_reindex';
reindexButton.attr('href', test_url)
@@ -360,11 +371,11 @@ define(["jquery", "common/js/spec_helpers/ajax_helpers", "common/js/components/u
it('shows an error message when reindexing fails', function() {
createCourseOutlinePage(this, mockSingleSectionCourseJSON);
var reindexSpy = spyOn(outlinePage, 'startReIndex').andCallThrough();
var errorSpy = spyOn(outlinePage, 'onIndexError').andCallThrough();
var reindexSpy = spyOn(outlinePage, 'startReIndex').and.callThrough();
var errorSpy = spyOn(outlinePage, 'onIndexError').and.callThrough();
var reindexButton = outlinePage.$('.button.button-reindex');
var test_url = '/course/5/search_reindex';
reindexButton.attr('href', test_url)
reindexButton.attr('href', test_url);
reindexButton.trigger('click');
AjaxHelpers.expectJsonRequest(requests, 'GET', test_url);
AjaxHelpers.respondWithError(requests, 500, createMockIndexJSON(false));

View File

@@ -40,9 +40,15 @@ define([
'content-group-editor', 'group-edit', 'list'
]);
this.addMatchers({
jasmine.addMatchers({
toBeExpanded: function () {
return Boolean($('a.group-toggle.hide-groups', $(this.actual)).length);
return {
compare: function (actual) {
return {
pass: Boolean($('a.group-toggle.hide-groups', $(actual)).length)
};
}
};
}
});
});
@@ -67,7 +73,7 @@ define([
});
it('should focus and expand if its id is part of url hash', function() {
spyOn(this.view, 'getLocationHash').andReturn('#0');
spyOn(this.view, 'getLocationHash').and.returnValue('#0');
this.view.render();
// We cannot use .toBeFocused due to flakiness.
expect($.fn.focus).toHaveBeenCalled();
@@ -75,14 +81,14 @@ define([
});
it('should not focus on any experiment configuration if url hash is empty', function() {
spyOn(this.view, 'getLocationHash').andReturn('');
spyOn(this.view, 'getLocationHash').and.returnValue('');
this.view.render();
expect($.fn.focus).not.toHaveBeenCalled();
expect(this.view.$(groupConfigItemClassName)).not.toBeExpanded();
});
it('should not focus on any experiment configuration if url hash contains wrong id', function() {
spyOn(this.view, 'getLocationHash').andReturn('#1');
spyOn(this.view, 'getLocationHash').and.returnValue('#1');
this.view.render();
expect($.fn.focus).not.toHaveBeenCalled();
expect(this.view.$(groupConfigItemClassName)).not.toBeExpanded();

View File

@@ -22,7 +22,7 @@ function ($, AjaxHelpers, ViewHelpers, ManageUsersFactory, ViewUtils) {
describe("read-write access", function() {
var mockHTML = readFixtures('mock/mock-manage-users-lib.underscore');
beforeEach(function () {
beforeEach(function (done) {
ViewHelpers.installMockAnalytics();
setFixtures(mockHTML);
appendSetFixtures($("<script>", { id: "team-member-tpl", type: "text/template"}).text(team_member_fixture));
@@ -37,9 +37,10 @@ function ($, AjaxHelpers, ViewHelpers, ManageUsersFactory, ViewUtils) {
10000,
true
);
waitsFor(function(){
return $(".ui-loading").length === 0;
}, "Waiting for backbone render to happen", 1000);
jasmine.waitUntil(function() {
return ($(".ui-loading").length === 0);
}).then(done);
});
afterEach(function () {

View File

@@ -47,7 +47,7 @@ define(
it("should render created timestamp correctly", function() {
var fakeDate = "fake formatted date";
spyOn(Date.prototype, "toLocaleString").andCallFake(
spyOn(Date.prototype, "toLocaleString").and.callFake(
function(locales, options) {
expect(locales).toEqual([]);
expect(options.timeZone).toEqual("UTC");

View File

@@ -1,6 +1,8 @@
define(["jquery", "common/js/spec_helpers/ajax_helpers", "common/js/spec_helpers/template_helpers",
"common/js/spec_helpers/view_helpers", "common/js/components/utils/view_utils", "js/views/unit_outline", "js/models/xblock_info"],
function ($, AjaxHelpers, TemplateHelpers, ViewHelpers, ViewUtils, UnitOutlineView, XBlockInfo) {
"common/js/spec_helpers/view_helpers", "common/js/components/utils/view_utils", "js/models/course",
"js/views/unit_outline", "js/models/xblock_info"],
function ($, AjaxHelpers, TemplateHelpers, ViewHelpers, ViewUtils,
Course, UnitOutlineView, XBlockInfo) {
describe("UnitOutlineView", function() {
var createUnitOutlineView, createMockXBlockInfo,
@@ -71,6 +73,14 @@ define(["jquery", "common/js/spec_helpers/ajax_helpers", "common/js/spec_helpers
};
beforeEach(function () {
window.course = new Course({
id: '5',
name: 'Course Name',
url_name: 'course_name',
org: 'course_org',
num: 'course_num',
revision: 'course_rev'
});
ViewHelpers.installMockAnalytics();
ViewHelpers.installViewTemplates();
TemplateHelpers.installTemplate('unit-outline');
@@ -78,6 +88,7 @@ define(["jquery", "common/js/spec_helpers/ajax_helpers", "common/js/spec_helpers
});
afterEach(function () {
delete window.course;
ViewHelpers.removeMockAnalytics();
});

View File

@@ -91,7 +91,7 @@ define(["jquery", "URI", "common/js/spec_helpers/ajax_helpers", "common/js/compo
var requests = AjaxHelpers.requests(this),
missingJavaScriptUrl = "no_such_file.js",
promise;
spyOn(ViewUtils, 'loadJavaScript').andReturn($.Deferred().reject().promise());
spyOn(ViewUtils, 'loadJavaScript').and.returnValue($.Deferred().reject().promise());
promise = postXBlockRequest(requests, [
["hash5", { mimetype: "application/javascript", kind: "url", data: missingJavaScriptUrl }]
]);
@@ -99,7 +99,7 @@ define(["jquery", "URI", "common/js/spec_helpers/ajax_helpers", "common/js/compo
});
it('Triggers an event to the runtime when a notification-action-button is clicked', function () {
var notifySpy = spyOn(xblockView, "notifyRuntime").andCallThrough();
var notifySpy = spyOn(xblockView, "notifyRuntime").and.callThrough();
postXBlockRequest(AjaxHelpers.requests(this), []);
xblockView.$el.find(".notification-action-button").click();

View File

@@ -3,9 +3,9 @@
* It is expected to be backed by a Group model.
*/
define([
'js/views/baseview'
'js/views/baseview', 'underscore', 'underscore.string', 'gettext', 'text!templates/group-edit.underscore'
],
function(BaseView) {
function(BaseView, _, str, gettext, groupEditTemplate) {
'use strict';
var ExperimentGroupEditView = BaseView.extend({
tagName: 'li',
@@ -22,7 +22,6 @@ function(BaseView) {
},
initialize: function() {
this.template = this.loadTemplate('group-edit');
this.listenTo(this.model, 'change', this.render);
},
@@ -30,7 +29,7 @@ function(BaseView) {
var collection = this.model.collection,
index = collection.indexOf(this.model);
this.$el.html(this.template({
this.$el.html(_.template(groupEditTemplate)({
name: this.model.get('name'),
allocation: this.getAllocation(),
index: index,

View File

@@ -1,4 +1,8 @@
define(["js/views/baseview", "underscore"], function(BaseView, _) {
define([
"js/views/baseview",
"underscore",
"text!templates/license-selector.underscore"
], function(BaseView, _, licenseSelectorTemplate) {
var defaultLicenseInfo = {
"all-rights-reserved": {
"name": gettext("All Rights Reserved"),
@@ -55,7 +59,6 @@ define(["js/views/baseview", "underscore"], function(BaseView, _) {
initialize: function(options) {
this.licenseInfo = options.licenseInfo || defaultLicenseInfo;
this.showPreview = !!options.showPreview; // coerce to boolean
this.template = this.loadTemplate("license-selector");
// Rerender when the model changes
this.listenTo(this.model, 'change', this.render);
@@ -79,7 +82,7 @@ define(["js/views/baseview", "underscore"], function(BaseView, _) {
},
render: function() {
this.$el.html(this.template({
this.$el.html(_.template(licenseSelectorTemplate)({
model: this.model.attributes,
licenseString: this.model.toString() || "",
licenseInfo: this.licenseInfo,

View File

@@ -48,10 +48,9 @@ lib_paths:
- xmodule_js/common_static/js/vendor/html5-input-polyfills/number-polyfill.js
- xmodule_js/common_static/js/vendor/sinon-1.17.0.js
- xmodule_js/common_static/js/vendor/Squire.js
- xmodule_js/common_static/js/vendor/jasmine-jquery.js
- xmodule_js/common_static/js/vendor/jasmine-stealth.js
- xmodule_js/common_static/js/libs/jasmine-stealth.js
- xmodule_js/common_static/js/libs/jasmine-waituntil.js
- xmodule_js/common_static/js/vendor/jasmine-imagediff.js
- xmodule_js/common_static/js/vendor/jasmine.async.js
- xmodule_js/common_static/js/vendor/CodeMirror/codemirror.js
- xmodule_js/common_static/js/vendor/jQuery-File-Upload/js
- xmodule_js/src/xmodule.js

View File

@@ -45,10 +45,7 @@ lib_paths:
- xmodule_js/common_static/js/vendor/html5-input-polyfills/number-polyfill.js
- xmodule_js/common_static/js/vendor/sinon-1.17.0.js
- xmodule_js/common_static/js/vendor/Squire.js
- xmodule_js/common_static/js/vendor/jasmine-jquery.js
- xmodule_js/common_static/js/vendor/jasmine-stealth.js
- xmodule_js/common_static/js/vendor/jasmine-imagediff.js
- xmodule_js/common_static/js/vendor/jasmine.async.js
- xmodule_js/common_static/js/vendor/CodeMirror/codemirror.js
- xmodule_js/common_static/js/vendor/domReady.js
- xmodule_js/common_static/js/vendor/URI.min.js

View File

@@ -0,0 +1,140 @@
// Common JavaScript tests, using RequireJS.
//
// To run all the tests and print results to the console:
//
// karma start cms/static/karma_cms.conf.js
//
//
// To run the tests for debugging: Debugging can be done in any browser
// but Chrome's developer console debugging experience is best.
//
// karma start cms/static/karma_cms.conf.js --browsers=BROWSER --single-run=false
//
//
// To run the tests with coverage and junit reports:
//
// karma start cms/static/karma_cms.conf.js --browsers=BROWSER --coverage
// --junitreportpath=<xunit_report_path> --coveragereportpath=<report_path>
//
// where `BROWSER` could be Chrome or Firefox.
//
/* jshint node: true */
/*jshint -W079 */
'use strict';
var path = require('path');
var _ = require('underscore');
var configModule = require(path.join(__dirname, '../../common/static/common/js/karma.common.conf.js'));
var libraryFiles = [
{pattern: 'xmodule_js/common_static/coffee/src/ajax_prefix.js', included: false},
{pattern: 'xmodule_js/common_static/js/src/utility.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/jquery.min.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/jquery-ui.min.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/jquery.cookie.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/jquery.simulate.js', included: false},
{pattern: 'xmodule_js/common_static/common/js/vendor/underscore.js', included: false},
{pattern: 'xmodule_js/common_static/common/js/vendor/underscore.string.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/backbone-min.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/backbone-associations-min.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/backbone.paginator.min.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/backbone-relational.min.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/timepicker/jquery.timepicker.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/jquery.leanModal.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/jquery.ajaxQueue.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/jquery.form.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/html5-input-polyfills/number-polyfill.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/sinon-1.17.0.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/Squire.js', included: false},
{pattern: 'xmodule_js/common_static/js/libs/jasmine-stealth.js', included: false},
{pattern: 'xmodule_js/common_static/js/libs/jasmine-waituntil.js', included: false},
{pattern: 'xmodule_js/common_static/js/libs/jasmine-extensions.js', included: true},
{pattern: 'xmodule_js/common_static/js/vendor/jasmine-imagediff.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/CodeMirror/codemirror.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/jQuery-File-Upload/js/**/*.js', included: false},
{pattern: 'xmodule_js/src/xmodule.js', included: false},
{pattern: 'xmodule_js/common_static/js/test/i18n.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/draggabilly.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/date.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/domReady.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/URI.min.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/jquery.smooth-scroll.min.js', included: false},
{pattern: 'xmodule_js/common_static/coffee/src/jquery.immediateDescendents.js', included: false},
{pattern: 'xmodule_js/common_static/js/xblock/**/*.js', included: false},
{pattern: 'xmodule_js/common_static/coffee/src/xblock/**/*.js', included: false},
{
pattern: 'xmodule_js/common_static/js/vendor/jQuery-File-Upload/js/jquery.iframe-transport.js',
included: false
},
{pattern: 'xmodule_js/common_static/js/vendor/jQuery-File-Upload/js/jquery.fileupload.js', included: false},
{
pattern: 'xmodule_js/common_static/js/vendor/jQuery-File-Upload/js/jquery.fileupload-process.js',
included: false
},
{
pattern: 'xmodule_js/common_static/js/vendor/jQuery-File-Upload/js/jquery.fileupload-validate.js',
included: false
},
{pattern: 'xmodule_js/common_static/js/vendor/mock-ajax.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/requirejs/text.js', included: false},
{pattern: 'edx-ui-toolkit/js/utils/global-loader.js', included: false},
{pattern: 'edx-pattern-library/js/modernizr-custom.js', included: false},
{pattern: 'edx-pattern-library/js/afontgarde.js', included: false},
{pattern: 'edx-pattern-library/js/edx-icons.js', included: false},
{pattern: 'edx-pattern-library/js/**/*.js', included: false},
{pattern: 'edx-ui-toolkit/js/**/*.js', included: false}
];
// Paths to source JavaScript files
var sourceFiles = [
{pattern: 'coffee/src/**/!(*spec).js', included: false},
{pattern: 'js/**/!(*spec).js', included: false},
{pattern: 'common/js/**/!(*spec).js', included: false}
];
// Paths to spec (test) JavaScript files
var specFiles = [
{pattern: 'coffee/spec/**/*spec.js', included: false},
{pattern: 'js/spec/**/*spec.js', included: false},
{pattern: 'js/certificates/spec/**/*spec.js', included: false}
];
// Paths to fixture files
var fixtureFiles = [
{pattern: 'coffee/fixtures/**/*.underscore', included: false},
{pattern: 'templates/**/*.underscore', included: false},
{pattern: 'common/templates/**/*.underscore', included: false}
];
// override fixture path and other config.
var runAndConfigFiles = [
{pattern: path.join(configModule.appRoot, 'common/static/common/js/jasmine.common.conf.js'), included: true},
'coffee/spec/main.js'
];
// do not include tests or libraries
// (these files will be instrumented by Istanbul)
var preprocessors = configModule.getPreprocessorObject(_.flatten([sourceFiles, specFiles]));
module.exports = function (config) {
var commonConfig = configModule.getConfig(config),
files = _.flatten([libraryFiles, sourceFiles, specFiles, fixtureFiles, runAndConfigFiles]),
localConfig;
// add nocache in files if coverage is not set
if (!config.coverage) {
files.forEach(function (f) {
if (_.isObject(f)) {
f.nocache = true;
}
});
}
localConfig = {
files: files,
preprocessors: preprocessors
};
config.set(_.extend(commonConfig, localConfig));
};

View File

@@ -0,0 +1,127 @@
// Common JavaScript tests, using RequireJS.
//
// To run all the tests and print results to the console:
//
// karma start cms/static/karma_cms_squire.conf.js
//
//
// To run the tests for debugging: Debugging can be done in any browser
// but Chrome's developer console debugging experience is best.
//
// karma start cms/static/karma_cms_squire.conf.js --browsers=BROWSER --single-run=false
//
//
// To run the tests with coverage and junit reports:
//
// karma start cms/static/karma_cms_squire.conf.js --browsers=BROWSER --coverage
// --junitreportpath=<xunit_report_path> --coveragereportpath=<report_path>
//
// where `BROWSER` could be Chrome or Firefox.
//
/* jshint node: true */
/*jshint -W079 */
'use strict';
var path = require('path');
var _ = require('underscore');
var configModule = require(path.join(__dirname, '../../common/static/common/js/karma.common.conf.js'));
var libraryFiles = [
{pattern: 'xmodule_js/common_static/js/vendor/requirejs/require.js', included: false},
{pattern: 'xmodule_js/common_static/coffee/src/ajax_prefix.js', included: false},
{pattern: 'xmodule_js/common_static/js/src/utility.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/jquery.min.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/jquery-ui.min.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/jquery.cookie.js', included: false},
{pattern: 'xmodule_js/common_static/common/js/vendor/underscore.js', included: false},
{pattern: 'xmodule_js/common_static/common/js/vendor/underscore.string.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/backbone-min.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/backbone-associations-min.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/backbone.paginator.min.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/timepicker/jquery.timepicker.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/jquery.leanModal.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/jquery.form.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/html5-input-polyfills/number-polyfill.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/sinon-1.17.0.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/Squire.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/jasmine-imagediff.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/CodeMirror/codemirror.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/domReady.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/URI.min.js', included: false},
{pattern: 'xmodule_js/common_static/js/libs/jasmine-extensions.js', included: true},
{pattern: 'xmodule_js/src/xmodule.js', included: false},
{pattern: 'xmodule_js/common_static/coffee/src/jquery.immediateDescendents.js', included: false},
{pattern: 'xmodule_js/common_static/js/test/i18n.js', included: false},
{pattern: 'xmodule_js/common_static/js/xblock/**/*.js', included: false},
{pattern: 'xmodule_js/common_static/coffee/src/xblock/**/*.js', included: false},
{pattern: 'xmodule_js/common_static/js/vendor/URI.min.js', included: false},
{
pattern: 'xmodule_js/common_static/js/vendor/jQuery-File-Upload/js/jquery.iframe-transport.js',
included: false
},
{pattern: 'xmodule_js/common_static/js/vendor/jQuery-File-Upload/js/jquery.fileupload.js', included: false},
{
pattern: 'xmodule_js/common_static/js/vendor/jQuery-File-Upload/js/jquery.fileupload-process.js',
included: false
},
{
pattern: 'xmodule_js/common_static/js/vendor/jQuery-File-Upload/js/jquery.fileupload-validate.js',
included: false
},
{pattern: 'xmodule_js/common_static/js/vendor/requirejs/text.js', included: false}
];
// Paths to source JavaScript files
var sourceFiles = [
{pattern: 'coffee/src/**/*.js', included: false},
{pattern: 'js/collections/**/*.js', included: false},
{pattern: 'js/models/**/*.js', included: false},
{pattern: 'js/utils/**/*.js', included: false},
{pattern: 'js/views/**/*.js', included: false},
{pattern: 'common/js/**/*.js', included: false}
];
// Paths to spec (test) JavaScript files
var specFiles = [
{pattern: 'coffee/spec/**/*.js', included: false},
{pattern: 'js/spec/**/*.js', included: false}
];
// Paths to fixture files
var fixtureFiles = [
{pattern: 'coffee/fixtures/**/*.*', included: false},
{pattern: 'templates/**/*.*', included: false},
{pattern: 'common/templates/**/*.*', included: false}
];
// override fixture path and other config.
var runAndConfigFiles = [
{pattern: path.join(configModule.appRoot, 'common/static/common/js/jasmine.common.conf.js'), included: true},
'coffee/spec/main_squire.js'
];
// do not include tests or libraries
// (these files will be instrumented by Istanbul)
var preprocessors = configModule.getPreprocessorObject(_.flatten([sourceFiles, specFiles]));
module.exports = function (config) {
var commonConfig = configModule.getConfig(config),
files = _.flatten([libraryFiles, sourceFiles, specFiles, fixtureFiles, runAndConfigFiles]),
localConfig;
// add nocache in files if coverage is not set
if (!config.coverage) {
files.forEach(function (f) {
if (_.isObject(f)) {
f.nocache = true;
}
});
}
localConfig = {
files: files,
preprocessors: preprocessors
};
config.set(_.extend(commonConfig, localConfig));
};

View File

@@ -1,6 +1,6 @@
<div class="xblock xblock-studio_view xmodule_edit xmodule_WrapperDescriptor" data-runtime-class="StudioRuntime"
data-init="XBlockToXModuleShim" data-runtime-version="1" data-usage-id="i4x:;_;_edX;_mock"
data-type="VerticalDescriptor" tabindex="0">
data-type="MockDescriptor" tabindex="0">
<div class="wrapper-comp-editor is-active" id="editor-tab" data-base-asset-url="/c4x/AndyA/ABT101/asset/">
<section class="editor-with-tabs">
<div class="edit-header">

View File

@@ -1,4 +1,4 @@
<div class="xblock xblock-studio_view xmodule_edit xmodule_WrapperDescriptor" data-runtime-class="StudioRuntime" data-init="XBlockToXModuleShim" data-runtime-version="1" data-usage-id="i4x:;_;_AndyA;_ABT101;_wrapper;_wrapper_l1_poll" data-type="VerticalDescriptor" tabindex="0">
<div class="xblock xblock-studio_view xmodule_edit xmodule_WrapperDescriptor" data-runtime-class="StudioRuntime" data-init="XBlockToXModuleShim" data-runtime-version="1" data-usage-id="i4x:;_;_AndyA;_ABT101;_wrapper;_wrapper_l1_poll" data-type="MockDescriptor" tabindex="0">
<section class="sequence-edit">
<script id="metadata-editor-tpl" type="text/template">
<ul class="list-input settings-list">

View File

@@ -4,7 +4,7 @@
<div
id="video_id"
class="video closed"
data-metadata='{"autohideHtml5": "true", "autoplay": "false", "captionDataDir": "", "endTime": "", "generalSpeed": "1.0", "saveStateUrl": "/save_user_state", "savedVideoPosition": "0", "showCaptions": "true", "sources": "[]", "speed": "1.5", "startTime": "", "streams": "0.5:7tqY6eQzVhE,1.0:cogebirgzzM,1.5:abcdefghijkl", "sub": "Z5KLxerq05Y", "transcriptAvailableTranslationsUrl": "/transcript/available_translations", "transcriptLanguage": "en", "transcriptLanguages": {"en": "English", "de": "Deutsch", "zh": "普通话"}, "transcriptTranslationUrl": "/transcript/translation/__lang__", "ytApiUrl": "www.youtube.com/iframe_api", "ytImageUrl": "", "ytTestTimeout": "1500", "ytMetadataUrl": "www.googleapis.com/youtube/v3/videos/"}'
data-metadata='{"autohideHtml5": "true", "autoplay": "false", "captionDataDir": "", "endTime": "", "generalSpeed": "1.0", "saveStateUrl": "/save_user_state", "savedVideoPosition": "0", "showCaptions": "true", "sources": [], "speed": "1.5", "startTime": "", "streams": "0.5:7tqY6eQzVhE,1.0:cogebirgzzM,1.5:abcdefghijkl", "sub": "Z5KLxerq05Y", "transcriptAvailableTranslationsUrl": "/transcript/available_translations", "transcriptLanguage": "en", "transcriptLanguages": {"en": "English", "de": "Deutsch", "zh": "普通话"}, "transcriptTranslationUrl": "/transcript/translation/__lang__", "ytApiUrl": "/base/fixtures/youtube_iframe_api.js", "ytImageUrl": "", "ytTestTimeout": "1500", "ytMetadataUrl": "www.googleapis.com/youtube/v3/videos/"}'
>
<div class="focus_grabber first"></div>

View File

@@ -4,7 +4,7 @@
<div
id="video_id"
class="video closed"
data-metadata='{"autohideHtml5": "true", "autoplay": "false", "captionDataDir": "", "endTime": "", "generalSpeed": "1.0", "saveStateUrl": "/save_user_state", "savedVideoPosition": "0", "showCaptions": "true", "sources": ["xmodule/include/fixtures/test.mp4","xmodule/include/fixtures/test.webm","xmodule/include/fixtures/test.ogv"], "speed": "1.5", "startTime": "", "streams": "", "sub": "Z5KLxerq05Y", "transcriptAvailableTranslationsUrl": "/transcript/available_translations", "transcriptLanguage": "en", "transcriptLanguages": {"en": "English", "de": "Deutsch", "zh": "普通话"}, "transcriptTranslationUrl": "/transcript/translation/__lang__", "ytApiUrl": "www.youtube.com/iframe_api", "ytImageUrl": "", "ytTestTimeout": "1500", "ytMetadataUrl": "www.googleapis.com/youtube/v3/videos/"}'
data-metadata='{"autohideHtml5": "true", "autoplay": "false", "captionDataDir": "", "endTime": "", "generalSpeed": "1.0", "saveStateUrl": "/save_user_state", "savedVideoPosition": "0", "showCaptions": "true", "sources": ["/base/fixtures/test.mp4","/base/fixtures/test.webm","/base/fixtures/test.ogv"], "speed": "1.5", "startTime": "", "streams": "", "sub": "Z5KLxerq05Y", "transcriptAvailableTranslationsUrl": "/transcript/available_translations", "transcriptLanguage": "en", "transcriptLanguages": {"en": "English", "de": "Deutsch", "zh": "普通话"}, "transcriptTranslationUrl": "/transcript/translation/__lang__", "ytApiUrl": "/base/fixtures/youtube_iframe_api.js", "ytImageUrl": "", "ytTestTimeout": "1500", "ytMetadataUrl": "www.googleapis.com/youtube/v3/videos/"}'
>
<div class="focus_grabber first"></div>

View File

@@ -4,7 +4,7 @@
<div
id="video_id"
class="video closed"
data-metadata='{"autohideHtml5": "true", "autoplay": "false", "captionDataDir": "", "endTime": "", "generalSpeed": "1.0", "saveStateUrl": "/save_user_state", "savedVideoPosition": "0", "showCaptions": "true", "sources": ["xmodule/include/fixtures/test.mp4","xmodule/include/fixtures/test.webm","xmodule/include/fixtures/test.ogv"], "speed": "1.5", "startTime": "", "streams": "", "sub": "Z5KLxerq05Y", "transcriptAvailableTranslationsUrl": "/transcript/available_translations", "transcriptLanguage": "en", "transcriptLanguages": {"en": "English", "de": "Deutsch", "zh": "普通话"}, "transcriptTranslationUrl": "/transcript/translation/__lang__", "ytApiUrl": "www.youtube.com/iframe_api", "ytImageUrl": "", "ytTestTimeout": "1500", "ytMetadataUrl": "www.googleapis.com/youtube/v3/videos/", "source": "", "html5_sources": ["http://youtu.be/3_yD_cEKoCk.mp4"]}'
data-metadata='{"autohideHtml5": "true", "autoplay": "false", "captionDataDir": "", "endTime": "", "generalSpeed": "1.0", "saveStateUrl": "/save_user_state", "savedVideoPosition": "0", "showCaptions": "true", "sources": ["/base/fixtures/test.mp4","/base/fixtures/test.webm","/base/fixtures/test.ogv"], "speed": "1.5", "startTime": "", "streams": "", "sub": "Z5KLxerq05Y", "transcriptAvailableTranslationsUrl": "/transcript/available_translations", "transcriptLanguage": "en", "transcriptLanguages": {"en": "English", "de": "Deutsch", "zh": "普通话"}, "transcriptTranslationUrl": "/transcript/translation/__lang__", "ytApiUrl": "/base/fixtures/youtube_iframe_api.js", "ytImageUrl": "", "ytTestTimeout": "1500", "ytMetadataUrl": "www.googleapis.com/youtube/v3/videos/", "source": "", "html5_sources": ["http://youtu.be/3_yD_cEKoCk.mp4"]}'
>
<div class="focus_grabber first"></div>

View File

@@ -4,7 +4,7 @@
<div
id="video_id"
class="video closed"
data-metadata='{"streams":"0.5:7tqY6eQzVhE,1.0:cogebirgzzM,1.5:abcdefghijkl", "showCaptions": false, "saveStateUrl": "/save_user_state", "savedVideoPosition": "0", "speed": "1.5", "startTime": "", "end": "", "transcriptAvailableTranslationsUrl": "/transcript/available_translations", "transcriptLanguage": "en", "transcriptLanguages": {"en": "English", "de": "Deutsch", "zh": "普通话"}, "transcriptTranslationUrl": "/transcript/translation/__lang__", "ytApiUrl": "www.youtube.com/iframe_api", "ytTestTimeout": "1500", "ytMetadataUrl": "www.googleapis.com/youtube/v3/videos/"}'
data-metadata='{"streams":"0.5:7tqY6eQzVhE,1.0:cogebirgzzM,1.5:abcdefghijkl", "showCaptions": false, "saveStateUrl": "/save_user_state", "savedVideoPosition": "0", "speed": "1.5", "startTime": "", "end": "", "transcriptAvailableTranslationsUrl": "/transcript/available_translations", "transcriptLanguage": "en", "transcriptLanguages": {"en": "English", "de": "Deutsch", "zh": "普通话"}, "transcriptTranslationUrl": "/transcript/translation/__lang__", "ytApiUrl": "/base/fixtures/youtube_iframe_api.js", "ytTestTimeout": "1500", "ytMetadataUrl": "www.googleapis.com/youtube/v3/videos/"}'
>
<div class="focus_grabber first"></div>

View File

@@ -4,9 +4,9 @@
<div
id="video_id"
class="video closed"
data-metadata='{"autohideHtml5": "true", "autoplay": "false", "captionDataDir": "", "endTime": "", "generalSpeed": "1.0", "saveStateUrl": "/save_user_state", "savedVideoPosition": "0", "showCaptions": "true", "sources": ["xmodule/include/fixtures/test.mp4","xmodule/include/fixtures/test.webm","xmodule/include/fixtures/test.ogv"], "speed": "1.5", "startTime": "", "streams": "", "sub": "Z5KLxerq05Y", "transcriptAvailableTranslationsUrl": "/transcript/available_translations", "transcriptLanguage": "en", "transcriptLanguages": {"en": "English", "de": "Deutsch", "zh": "普通话"}, "transcriptTranslationUrl": "/transcript/translation/__lang__", "ytApiUrl": "www.youtube.com/iframe_api", "ytImageUrl": "", "ytTestTimeout": "1500", "ytMetadataUrl": "www.googleapis.com/youtube/v3/videos/"}'
data-bumper-metadata='{"transcriptLanguage": "en", "showCaptions": "true", "transcriptLanguages": {"en": "English", "de": "Deutsch", "zh": "普通话"}, "sources": ["xmodule/include/fixtures/test.mp4","xmodule/include/fixtures/test.webm","xmodule/include/fixtures/test.ogv"], "transcriptTranslationUrl": "/transcript/translation/__lang__/?is_bumper=1", "transcriptAvailableTranslationsUrl": "/transcript/available_translations/?is_bumper=1", "streams": "", "saveStateUrl": "/save_user_state"}'
data-poster='{"url": "xmodule/include/fixtures/poster.jpg", "type": "youtube"}'
data-metadata='{"autohideHtml5": "true", "autoplay": "false", "captionDataDir": "", "endTime": "", "generalSpeed": "1.0", "saveStateUrl": "/save_user_state", "savedVideoPosition": "0", "showCaptions": "true", "sources": ["/base/fixtures/test.mp4","/base/fixtures/test.webm","/base/fixtures/test.ogv"], "speed": "1.5", "startTime": "", "streams": "", "sub": "Z5KLxerq05Y", "transcriptAvailableTranslationsUrl": "/transcript/available_translations", "transcriptLanguage": "en", "transcriptLanguages": {"en": "English", "de": "Deutsch", "zh": "普通话"}, "transcriptTranslationUrl": "/transcript/translation/__lang__", "ytApiUrl": "/base/fixtures/youtube_iframe_api.js", "ytImageUrl": "", "ytTestTimeout": "1500", "ytMetadataUrl": "www.googleapis.com/youtube/v3/videos/"}'
data-bumper-metadata='{"transcriptLanguage": "en", "showCaptions": "true", "transcriptLanguages": {"en": "English", "de": "Deutsch", "zh": "普通话"}, "sources": ["/base/fixtures/test.mp4","/base/fixtures/test.webm","/base/fixtures/test.ogv"], "transcriptTranslationUrl": "/transcript/translation/__lang__/?is_bumper=1", "transcriptAvailableTranslationsUrl": "/transcript/available_translations/?is_bumper=1", "streams": "", "saveStateUrl": "/save_user_state"}'
data-poster='{"url": "/base/fixtures/poster.jpg", "type": "youtube"}'
>
<div class="focus_grabber first"></div>

View File

@@ -4,7 +4,7 @@
<div
id="video_id1"
class="video closed"
data-metadata='{"autohideHtml5": "true", "autoplay": "false", "captionDataDir": "", "endTime": "", "generalSpeed": "1.0", "saveStateUrl": "/save_user_state", "savedVideoPosition": "0", "showCaptions": "true", "sources": ["xmodule/include/fixtures/test.mp4","xmodule/include/fixtures/test.webm","xmodule/include/fixtures/test.ogv"], "speed": "1.5", "startTime": "", "streams": "0.5:7tqY6eQzVhE,1.0:cogebirgzzM,1.5:abcdefghijkl", "sub": "", "transcriptAvailableTranslationsUrl": "/transcript/available_translations", "transcriptLanguage": "en", "transcriptLanguages": {"en": "English", "de": "Deutsch", "zh": "普通话"}, "transcriptTranslationUrl": "/transcript/translation/__lang__", "ytApiUrl": "www.youtube.com/iframe_api", "ytImageUrl": "", "ytTestTimeout": "1500", "ytMetadataUrl": "www.googleapis.com/youtube/v3/videos/"}'
data-metadata='{"autohideHtml5": "true", "autoplay": "false", "captionDataDir": "", "endTime": "", "generalSpeed": "1.0", "saveStateUrl": "/save_user_state", "savedVideoPosition": "0", "showCaptions": "true", "sources": ["/base/fixtures/test.mp4","/base/fixtures/test.webm","/base/fixtures/test.ogv"], "speed": "1.5", "startTime": "", "streams": "0.5:7tqY6eQzVhE,1.0:cogebirgzzM,1.5:abcdefghijkl", "sub": "", "transcriptAvailableTranslationsUrl": "/transcript/available_translations", "transcriptLanguage": "en", "transcriptLanguages": {"en": "English", "de": "Deutsch", "zh": "普通话"}, "transcriptTranslationUrl": "/transcript/translation/__lang__", "ytApiUrl": "/base/fixtures/youtube_iframe_api.js", "ytImageUrl": "", "ytTestTimeout": "1500", "ytMetadataUrl": "www.googleapis.com/youtube/v3/videos/"}'
>
<div class="focus_grabber first"></div>
@@ -38,7 +38,7 @@
<div
id="video_id2"
class="video"
data-metadata='{"autohideHtml5": "true", "autoplay": "false", "captionDataDir": "", "endTime": "", "generalSpeed": "1.0", "saveStateUrl": "/save_user_state", "savedVideoPosition": "0", "showCaptions": "true", "sources": ["xmodule/include/fixtures/test.mp4","xmodule/include/fixtures/test.webm","xmodule/include/fixtures/test.ogv"], "speed": "1.0", "startTime": "", "streams": "0.75:7tqY6eQzVhE,1.0:cogebirgzzM", "sub": "", "transcriptAvailableTranslationsUrl": "/transcript/available_translations", "transcriptLanguage": "en", "transcriptLanguages": {"en": "English", "de": "Deutsch", "zh": "普通话"}, "transcriptTranslationUrl": "/transcript/translation/__lang__", "ytApiUrl": "www.youtube.com/iframe_api", "ytImageUrl": "", "ytTestTimeout": "1500", "ytMetadataUrl": "www.googleapis.com/youtube/v3/videos/"}'
data-metadata='{"autohideHtml5": "true", "autoplay": "false", "captionDataDir": "", "endTime": "", "generalSpeed": "1.0", "saveStateUrl": "/save_user_state", "savedVideoPosition": "0", "showCaptions": "true", "sources": ["/base/fixtures/test.mp4","/base/fixtures/test.webm","/base/fixtures/test.ogv"], "speed": "1.0", "startTime": "", "streams": "0.75:7tqY6eQzVhE,1.0:cogebirgzzM", "sub": "", "transcriptAvailableTranslationsUrl": "/transcript/available_translations", "transcriptLanguage": "en", "transcriptLanguages": {"en": "English", "de": "Deutsch", "zh": "普通话"}, "transcriptTranslationUrl": "/transcript/translation/__lang__", "ytApiUrl": "/base/fixtures/youtube_iframe_api.js", "ytImageUrl": "", "ytTestTimeout": "1500", "ytMetadataUrl": "www.googleapis.com/youtube/v3/videos/"}'
>
<div class="tc-wrapper">
<article class="video-wrapper">
@@ -68,7 +68,7 @@
<div
id="video_id3"
class="video"
data-metadata='{"autohideHtml5": "true", "autoplay": "false", "captionDataDir": "", "endTime": "", "generalSpeed": "1.0", "saveStateUrl": "/save_user_state", "savedVideoPosition": "0", "showCaptions": "true", "sources": ["xmodule/include/fixtures/test.mp4","xmodule/include/fixtures/test.webm","xmodule/include/fixtures/test.ogv"], "speed": "1.0", "startTime": "", "streams": "0.75:7tqY6eQzVhE,1.0:cogebirgzzM", "sub": "", "transcriptAvailableTranslationsUrl": "/transcript/available_translations", "transcriptLanguage": "en", "transcriptLanguages": {"en": "English", "de": "Deutsch", "zh": "普通话"}, "transcriptTranslationUrl": "/transcript/translation/__lang__", "ytApiUrl": "www.youtube.com/iframe_api", "ytImageUrl": "", "ytTestTimeout": "1500", "ytMetadataUrl": "www.googleapis.com/youtube/v3/videos/"}'
data-metadata='{"autohideHtml5": "true", "autoplay": "false", "captionDataDir": "", "endTime": "", "generalSpeed": "1.0", "saveStateUrl": "/save_user_state", "savedVideoPosition": "0", "showCaptions": "true", "sources": ["/base/fixtures/test.mp4","/base/fixtures/test.webm","/base/fixtures/test.ogv"], "speed": "1.0", "startTime": "", "streams": "0.75:7tqY6eQzVhE,1.0:cogebirgzzM", "sub": "", "transcriptAvailableTranslationsUrl": "/transcript/available_translations", "transcriptLanguage": "en", "transcriptLanguages": {"en": "English", "de": "Deutsch", "zh": "普通话"}, "transcriptTranslationUrl": "/transcript/translation/__lang__", "ytApiUrl": "/base/fixtures/youtube_iframe_api.js", "ytImageUrl": "", "ytTestTimeout": "1500", "ytMetadataUrl": "www.googleapis.com/youtube/v3/videos/"}'
>
<div class="tc-wrapper">
<article class="video-wrapper">

View File

@@ -36,8 +36,8 @@ lib_paths:
- common_static/js/test/i18n.js
- common_static/coffee/src/ajax_prefix.js
- common_static/js/src/logger.js
- common_static/js/vendor/jasmine-jquery.js
- common_static/js/vendor/jasmine-imagediff.js
- common_static/js/libs/jasmine-waituntil.js
- common_static/js/vendor/requirejs/require.js
- RequireJS-namespace-undefine.js
- common_static/js/vendor/jquery.min.js

View File

@@ -0,0 +1,10 @@
// overwrite the loaded method and manually start the karma after a delay
// Somehow the code initialized in jQuery's onready doesn't get called before karma auto starts
/* jshint node: true */
'use strict';
window.__karma__.loaded = function () {
setTimeout(function () {
window.__karma__.start();
}, 1000);
};

View File

@@ -0,0 +1,125 @@
// Xmodule Tests
//
// To run all the tests and print results to the console:
//
// karma start common/lib/xmodule/xmodule/js/karma_xmodule.conf.js
//
//
// To run the tests for debugging: Debugging can be done in any browser
// Chrome's developer console debugging experience is the best though
//
// karma start common/lib/xmodule/xmodule/js/karma-xmodule.conf.js --browsers=BROWSER --single-run=false
//
//
// To run the tests with coverage and junit reports:
//
// karma start common/lib/xmodule/xmodule/js/karma-xmodule.conf.js
// --browsers=BROWSER --coverage --junitreportpath=<xunit_report_path> --coveragereportpath=<report_path>
//
// where `BROWSER` could be Chrome or Firefox.
//
/* jshint node: true */
/*jshint -W079 */
'use strict';
var path = require('path');
var _ = require('underscore');
var configModule = require(path.join(__dirname, 'common_static/common/js/karma.common.conf.js'));
var libraryFiles = [
// override fixture path and other config.
{pattern: path.join(configModule.appRoot, 'common/static/common/js/jasmine.common.conf.js'), included: true},
{pattern: 'common_static/js/vendor/jquery.min.js', included: true},
{pattern: 'common_static/js/test/i18n.js', included: true},
{pattern: 'common_static/coffee/src/ajax_prefix.js', included: true},
{pattern: 'common_static/js/src/logger.js', included: true},
{pattern: 'common_static/js/vendor/jasmine-imagediff.js', included: true},
{pattern: 'common_static/js/libs/jasmine-waituntil.js', included: true},
{pattern: 'common_static/js/libs/jasmine-extensions.js', included: true},
{pattern: 'common_static/js/vendor/requirejs/require.js', included: true},
{pattern: 'RequireJS-namespace-undefine.js', included: true},
{pattern: 'common_static/js/vendor/jquery-ui.min.js', included: true},
{pattern: 'common_static/js/vendor/jquery.ui.draggable.js', included: true},
{pattern: 'common_static/js/vendor/jquery.cookie.js', included: true},
{pattern: 'common_static/js/vendor/json2.js', included: true},
{pattern: 'common_static/common/js/vendor/underscore.js', included: true},
{pattern: 'common_static/js/vendor/backbone-min.js', included: true},
{pattern: 'common_static/js/vendor/jquery.leanModal.js', included: true},
{pattern: 'common_static/js/vendor/CodeMirror/codemirror.js', included: true},
{pattern: 'common_static/js/vendor/tinymce/js/tinymce/jquery.tinymce.min.js', included: true},
{pattern: 'common_static/js/vendor/tinymce/js/tinymce/tinymce.full.min.js', included: true},
{pattern: 'common_static/js/vendor/jquery.timeago.js', included: true},
{pattern: 'common_static/js/vendor/sinon-1.17.0.js', included: true},
{pattern: 'common_static/js/test/add_ajax_prefix.js', included: true},
{pattern: 'common_static/js/src/utility.js', included: true},
{pattern: 'public/js/split_test_staff.js', included: true},
{pattern: 'common_static/js/src/accessibility_tools.js', included: true},
{pattern: 'common_static/js/vendor/moment.min.js', included: true},
{pattern: 'spec/main_requirejs.js', included: true},
{pattern: 'src/word_cloud/d3.min.js', included: true},
{pattern: 'common_static/js/vendor/draggabilly.js', included: false},
{pattern: 'common_static/edx-ui-toolkit/js/utils/global-loader.js', included: true},
{pattern: 'common_static/edx-pattern-library/js/modernizr-custom.js', included: false},
{pattern: 'common_static/edx-pattern-library/js/afontgarde.js', included: false},
{pattern: 'common_static/edx-pattern-library/js/edx-icons.js', included: false}
];
// Paths to source JavaScript files
var sourceFiles = [
{pattern: 'src/xmodule.js', included: true, skipInstrument: true},
{pattern: 'src/**/*.js', included: true}
];
// Paths to spec (test) JavaScript files
var specFiles = [
{pattern: 'spec/helper.js', included: true, skipInstrument: true},
{pattern: 'spec/**/*.js', included: true}
];
// Paths to fixture files
var fixtureFiles = [
{pattern: 'fixtures/*.*', included: false, served: true}
];
var runAndConfigFiles = [
{pattern: 'karma_runner.js', included: true}
];
// do not include tests or libraries
// (these files will be instrumented by Istanbul)
var preprocessors = (function () {
var preprocessFiles = {};
_.flatten([sourceFiles, specFiles]).forEach(function (file) {
var pattern = _.isObject(file) ? file.pattern : file;
if (!file.skipInstrument) {
preprocessFiles[pattern] = ['coverage'];
}
});
return preprocessFiles;
}());
module.exports = function (config) {
var commonConfig = configModule.getConfig(config, false),
files = _.flatten([libraryFiles, sourceFiles, specFiles, fixtureFiles, runAndConfigFiles]),
localConfig;
// add nocache in files if coverage is not set
if (!config.coverage) {
files.forEach(function (f) {
if (_.isObject(f)) {
f.nocache = true;
}
});
}
localConfig = {
files: files,
preprocessors: preprocessors
};
config.set(_.extend(commonConfig, localConfig));
};

View File

@@ -7,7 +7,7 @@ describe 'Problem', ->
Hub: jasmine.createSpyObj('MathJax.Hub', ['getAllJax', 'Queue'])
Callback: jasmine.createSpyObj('MathJax.Callback', ['After'])
@stubbedJax = root: jasmine.createSpyObj('jax.root', ['toMathML'])
MathJax.Hub.getAllJax.andReturn [@stubbedJax]
MathJax.Hub.getAllJax.and.returnValue [@stubbedJax]
window.update_schematics = ->
spyOn SR, 'readElts'
spyOn SR, 'readText'
@@ -21,8 +21,8 @@ describe 'Problem', ->
loadFixtures 'problem.html'
spyOn Logger, 'log'
spyOn($.fn, 'load').andCallFake (url, callback) ->
$(@).html problem_content_default
spyOn($.fn, 'load').and.callFake (url, callback) ->
$(@).html readFixtures('problem_content.html')
callback()
describe 'constructor', ->
@@ -46,7 +46,7 @@ describe 'Problem', ->
describe 'bind', ->
beforeEach ->
spyOn window, 'update_schematics'
MathJax.Hub.getAllJax.andReturn [@stubbedJax]
MathJax.Hub.getAllJax.and.returnValue [@stubbedJax]
@problem = new Problem($('.xblock-student_view'))
it 'set mathjax typeset', ->
@@ -76,7 +76,7 @@ describe 'Problem', ->
describe 'bind_with_custom_input_id', ->
beforeEach ->
spyOn window, 'update_schematics'
MathJax.Hub.getAllJax.andReturn [@stubbedJax]
MathJax.Hub.getAllJax.and.returnValue [@stubbedJax]
@problem = new Problem($('.xblock-student_view'))
$(@).html readFixtures('problem_content_1240.html')
@@ -137,7 +137,7 @@ describe 'Problem', ->
describe 'with no content given', ->
beforeEach ->
spyOn($, 'postWithPrefix').andCallFake (url, callback) ->
spyOn($, 'postWithPrefix').and.callFake (url, callback) ->
callback html: "Hello World"
@problem.render()
@@ -164,7 +164,7 @@ describe 'Problem', ->
@problem.answers = 'foo=1&bar=2'
it 'log the problem_check event', ->
spyOn($, 'postWithPrefix').andCallFake (url, answers, callback) ->
spyOn($, 'postWithPrefix').and.callFake (url, answers, callback) ->
promise =
always: (callable) -> callable()
done: (callable) -> callable()
@@ -172,7 +172,7 @@ describe 'Problem', ->
expect(Logger.log).toHaveBeenCalledWith 'problem_check', 'foo=1&bar=2'
it 'log the problem_graded event, after the problem is done grading.', ->
spyOn($, 'postWithPrefix').andCallFake (url, answers, callback) ->
spyOn($, 'postWithPrefix').and.callFake (url, answers, callback) ->
response =
success: 'correct'
contents: 'mock grader response'
@@ -184,7 +184,7 @@ describe 'Problem', ->
expect(Logger.log).toHaveBeenCalledWith 'problem_graded', ['foo=1&bar=2', 'mock grader response'], @problem.id
it 'submit the answer for check', ->
spyOn($, 'postWithPrefix').andCallFake (url, answers, callback) ->
spyOn($, 'postWithPrefix').and.callFake (url, answers, callback) ->
promise =
always: (callable) -> callable()
done: (callable) -> callable()
@@ -194,58 +194,76 @@ describe 'Problem', ->
describe 'when the response is correct', ->
it 'call render with returned content', ->
spyOn($, 'postWithPrefix').andCallFake (url, answers, callback) ->
callback(success: 'correct', contents: 'Correct!')
spyOn($, 'postWithPrefix').and.callFake (url, answers, callback) ->
callback(success: 'correct', contents: 'Correct')
promise =
always: (callable) -> callable()
done: (callable) -> callable()
@problem.check()
expect(@problem.el.html()).toEqual 'Correct!'
expect(@problem.el.html()).toEqual 'Correct'
expect(window.SR.readElts).toHaveBeenCalled()
describe 'when the response is incorrect', ->
it 'call render with returned content', ->
spyOn($, 'postWithPrefix').andCallFake (url, answers, callback) ->
callback(success: 'incorrect', contents: 'Incorrect!')
spyOn($, 'postWithPrefix').and.callFake (url, answers, callback) ->
callback(success: 'incorrect', contents: 'Incorrect')
promise =
always: (callable) -> callable()
done: (callable) -> callable()
@problem.check()
expect(@problem.el.html()).toEqual 'Incorrect!'
expect(@problem.el.html()).toEqual 'Incorrect'
expect(window.SR.readElts).toHaveBeenCalled()
it 'tests if all the capa buttons are disabled while checking', ->
runs ->
spyOn($, 'postWithPrefix').andCallFake (url, answers, callback) ->
callback(success: 'incorrect', contents: 'Incorrect!')
it 'tests if all the capa buttons are disabled while checking', (done)->
deferred = $.Deferred()
self = this
runs = ->
spyOn($, 'postWithPrefix').and.callFake (url, answers, callback) ->
promise = undefined
callback
success: 'incorrect'
contents: 'Incorrect'
promise =
always: (callable) -> callable()
done: (callable) -> callable()
always: (callable) ->
callable()
done: (callable) ->
callable()
spyOn @problem, 'enableAllButtons'
@problem.check()
expect(@problem.enableAllButtons).toHaveBeenCalledWith false, true
waitsFor (->
return jQuery.active == 0
), "jQuery requests finished", 1000
if jQuery.active == 0
deferred.resolve()
deferred.promise()
runs ->
expect(@problem.enableAllButtons).toHaveBeenCalledWith true, true
runs.call(self).then(->
expect(self.problem.enableAllButtons).toHaveBeenCalledWith true, true
return
).always done
it 'tests the expected change in text of check button', ->
runs ->
spyOn($, 'postWithPrefix').andCallFake (url, answers, callback) ->
it 'tests the expected change in text of check button', (done) ->
deferred = $.Deferred()
self = this
runs = ->
spyOn($, 'postWithPrefix').and.callFake (url, answers, callback) ->
promise = undefined
promise =
always: (callable) -> callable()
done: (callable) -> callable()
always: (callable) ->
callable()
done: (callable) ->
callable()
spyOn @problem.checkButtonLabel, 'text'
@problem.check()
expect(@problem.checkButtonLabel.text).toHaveBeenCalledWith 'Checking...'
waitsFor (->
return jQuery.active == 0
), "jQuery requests finished", 1000
if jQuery.active == 0
deferred.resolve()
deferred.promise()
runs ->
expect(@problem.checkButtonLabel.text).toHaveBeenCalledWith 'Check'
runs.call(self).then(->
expect(self.problem.checkButtonLabel.text).toHaveBeenCalledWith 'Check'
return
).always done
describe 'check button on problems', ->
beforeEach ->
@@ -341,7 +359,7 @@ describe 'Problem', ->
@problem = new Problem($('.xblock-student_view'))
it 'log the problem_reset event', ->
spyOn($, 'postWithPrefix').andCallFake (url, answers, callback) ->
spyOn($, 'postWithPrefix').and.callFake (url, answers, callback) ->
promise =
always: (callable) -> callable()
@problem.answers = 'foo=1&bar=2'
@@ -349,7 +367,7 @@ describe 'Problem', ->
expect(Logger.log).toHaveBeenCalledWith 'problem_reset', 'foo=1&bar=2'
it 'POST to the problem reset page', ->
spyOn($, 'postWithPrefix').andCallFake (url, answers, callback) ->
spyOn($, 'postWithPrefix').and.callFake (url, answers, callback) ->
promise =
always: (callable) -> callable()
@problem.reset()
@@ -357,29 +375,34 @@ describe 'Problem', ->
{ id: 'i4x://edX/101/problem/Problem1' }, jasmine.any(Function)
it 'render the returned content', ->
spyOn($, 'postWithPrefix').andCallFake (url, answers, callback) ->
callback html: "Reset!"
spyOn($, 'postWithPrefix').and.callFake (url, answers, callback) ->
callback html: "Reset"
promise =
always: (callable) -> callable()
@problem.reset()
expect(@problem.el.html()).toEqual 'Reset!'
expect(@problem.el.html()).toEqual 'Reset'
it 'tests if all the buttons are disabled and the text of check button remains same while resetting', ->
runs ->
spyOn($, 'postWithPrefix').andCallFake (url, answers, callback) ->
promise =
always: (callable) -> callable()
it 'tests if all the buttons are disabled and the text of check button remains same while resetting', (done) ->
deferred = $.Deferred()
self = this
runs = ->
spyOn($, 'postWithPrefix').and.callFake (url, answers, callback) ->
promise = undefined
promise = always: (callable) ->
callable()
spyOn @problem, 'enableAllButtons'
@problem.reset()
expect(@problem.enableAllButtons).toHaveBeenCalledWith false, false
expect(@problem.checkButtonLabel).toHaveText 'Check'
waitsFor (->
return jQuery.active == 0
), "jQuery requests finished", 1000
if jQuery.active == 0
deferred.resolve()
deferred.promise()
runs ->
expect(@problem.enableAllButtons).toHaveBeenCalledWith true, false
expect(@problem.checkButtonLabel).toHaveText 'Check'
runs.call(self).then(->
expect(self.problem.enableAllButtons).toHaveBeenCalledWith true, false
expect(self.problem.checkButtonLabel).toHaveText 'Check'
).always done
describe 'show', ->
beforeEach ->
@@ -402,20 +425,20 @@ describe 'Problem', ->
jasmine.any(Function)
it 'show the answers', ->
spyOn($, 'postWithPrefix').andCallFake (url, callback) ->
spyOn($, 'postWithPrefix').and.callFake (url, callback) ->
callback answers: '1_1': 'One', '1_2': 'Two'
@problem.show()
expect($('#answer_1_1')).toHaveHtml 'One'
expect($('#answer_1_2')).toHaveHtml 'Two'
it 'toggle the show answer button', ->
spyOn($, 'postWithPrefix').andCallFake (url, callback) -> callback(answers: {})
spyOn($, 'postWithPrefix').and.callFake (url, callback) -> callback(answers: {})
@problem.show()
expect($('.show .show-label')).toHaveText 'Hide Answer'
expect(window.SR.readElts).toHaveBeenCalled()
it 'toggle the show answer button, answers are strings', ->
spyOn($, 'postWithPrefix').andCallFake (url, callback) -> callback(answers: '1_1': 'One', '1_2': 'Two')
spyOn($, 'postWithPrefix').and.callFake (url, callback) -> callback(answers: '1_1': 'One', '1_2': 'Two')
@problem.show()
expect($('.show .show-label')).toHaveText 'Hide Answer'
expect(window.SR.readElts).toHaveBeenCalledWith ['<p>Answer: One</p>', '<p>Answer: Two</p>']
@@ -423,27 +446,32 @@ describe 'Problem', ->
it 'toggle the show answer button, answers are elements', ->
answer1 = '<div><span class="detailed-solution">one</span></div>'
answer2 = '<div><span class="detailed-solution">two</span></div>'
spyOn($, 'postWithPrefix').andCallFake (url, callback) -> callback(answers: '1_1': answer1, '1_2': answer2)
spyOn($, 'postWithPrefix').and.callFake (url, callback) -> callback(answers: '1_1': answer1, '1_2': answer2)
@problem.show()
expect($('.show .show-label')).toHaveText 'Hide Answer'
expect(window.SR.readElts).toHaveBeenCalledWith [jasmine.any(jQuery), jasmine.any(jQuery)]
it 'add the showed class to element', ->
spyOn($, 'postWithPrefix').andCallFake (url, callback) -> callback(answers: {})
spyOn($, 'postWithPrefix').and.callFake (url, callback) -> callback(answers: {})
@problem.show()
expect(@problem.el).toHaveClass 'showed'
it 'reads the answers', ->
runs ->
spyOn($, 'postWithPrefix').andCallFake (url, callback) -> callback(answers: 'answers')
it 'reads the answers', (done) ->
deferred = $.Deferred()
runs = ->
spyOn($, 'postWithPrefix').and.callFake (url, callback) ->
callback answers:
'1_1': 'answers'
@problem.show()
if jQuery.active == 0
deferred.resolve()
deferred.promise()
waitsFor (->
return jQuery.active == 0
), "jQuery requests finished", 1000
runs ->
runs.call(this).then(->
expect(window.SR.readElts).toHaveBeenCalled()
return
).always done
describe 'multiple choice question', ->
beforeEach ->
@@ -455,7 +483,7 @@ describe 'Problem', ->
'''
it 'set the correct_answer attribute on the choice', ->
spyOn($, 'postWithPrefix').andCallFake (url, callback) ->
spyOn($, 'postWithPrefix').and.callFake (url, callback) ->
callback answers: '1_1': [2, 3]
@problem.show()
expect($('label[for="input_1_1_1"]')).not.toHaveAttr 'correct_answer', 'true'
@@ -496,7 +524,7 @@ describe 'Problem', ->
@problem.el.prepend(radio_text_xml)
it 'sets the correct class on the section for the correct choice', ->
spyOn($, 'postWithPrefix').andCallFake (url, callback) ->
spyOn($, 'postWithPrefix').and.callFake (url, callback) ->
callback answers: "1_2_1": ["1_2_1_choiceinput_0bc"], "1_2_1_choiceinput_0bc": "3"
@problem.show()
@@ -507,7 +535,7 @@ describe 'Problem', ->
expect($('#answer_1_2_1_choiceinput_2bc').text()).toEqual('')
it 'Should not disable input fields', ->
spyOn($, 'postWithPrefix').andCallFake (url, callback) ->
spyOn($, 'postWithPrefix').and.callFake (url, callback) ->
callback answers: "1_2_1": ["1_2_1_choiceinput_0bc"], "1_2_1_choiceinput_0bc": "3"
@problem.show()
expect($('input#1_2_1_choiceinput_0bc').attr('disabled')).not.toEqual('disabled')
@@ -537,7 +565,7 @@ describe 'Problem', ->
expect(img).toImageDiffEqual(el.find('canvas')[0])
stubRequest = (data) =>
spyOn($, 'postWithPrefix').andCallFake (url, callback) ->
spyOn($, 'postWithPrefix').and.callFake (url, callback) ->
callback data
getImage = (coords, c_width, c_height) =>
@@ -680,51 +708,61 @@ describe 'Problem', ->
@problem.answers = 'foo=1&bar=2'
it 'log the problem_save event', ->
spyOn($, 'postWithPrefix').andCallFake (url, answers, callback) ->
spyOn($, 'postWithPrefix').and.callFake (url, answers, callback) ->
promise =
always: (callable) -> callable()
@problem.save()
expect(Logger.log).toHaveBeenCalledWith 'problem_save', 'foo=1&bar=2'
it 'POST to save problem', ->
spyOn($, 'postWithPrefix').andCallFake (url, answers, callback) ->
spyOn($, 'postWithPrefix').and.callFake (url, answers, callback) ->
promise =
always: (callable) -> callable()
@problem.save()
expect($.postWithPrefix).toHaveBeenCalledWith '/problem/Problem1/problem_save',
'foo=1&bar=2', jasmine.any(Function)
it 'reads the save message', ->
runs ->
spyOn($, 'postWithPrefix').andCallFake (url, answers, callback) ->
callback(success: 'OK')
promise =
always: (callable) -> callable()
it 'reads the save message', (done) ->
deferred = $.Deferred()
runs = ->
spyOn($, 'postWithPrefix').and.callFake (url, answers, callback) ->
promise = undefined
callback success: 'OK'
promise = always: (callable) ->
callable()
@problem.save()
waitsFor (->
return jQuery.active == 0
), "jQuery requests finished", 1000
if jQuery.active == 0
deferred.resolve()
deferred.promise()
runs ->
runs.call(this).then(->
expect(window.SR.readElts).toHaveBeenCalled()
return
).always done
it 'tests if all the buttons are disabled and the text of check button does not change while saving.', ->
runs ->
spyOn($, 'postWithPrefix').andCallFake (url, answers, callback) ->
callback(success: 'OK')
promise =
always: (callable) -> callable()
it 'tests if all the buttons are disabled and the text of check button does not change while saving.', (done) ->
deferred = $.Deferred()
self = this
runs = ->
spyOn($, 'postWithPrefix').and.callFake (url, answers, callback) ->
promise = undefined
callback success: 'OK'
promise = always: (callable) ->
callable()
spyOn @problem, 'enableAllButtons'
@problem.save()
expect(@problem.enableAllButtons).toHaveBeenCalledWith false, false
expect(@problem.checkButtonLabel).toHaveText 'Check'
waitsFor (->
return jQuery.active == 0
), "jQuery requests finished", 1000
if jQuery.active == 0
deferred.resolve()
deferred.promise()
runs ->
expect(@problem.enableAllButtons).toHaveBeenCalledWith true, false
expect(@problem.checkButtonLabel).toHaveText 'Check'
runs.call(self).then(->
expect(self.problem.enableAllButtons).toHaveBeenCalledWith true, false
expect(self.problem.checkButtonLabel).toHaveText 'Check'
).always done
describe 'refreshMath', ->
beforeEach ->
@@ -739,7 +777,7 @@ describe 'Problem', ->
describe 'updateMathML', ->
beforeEach ->
@problem = new Problem($('.xblock-student_view'))
@stubbedJax.root.toMathML.andReturn '<MathML>'
@stubbedJax.root.toMathML.and.returnValue '<MathML>'
describe 'when there is no exception', ->
beforeEach ->
@@ -750,7 +788,9 @@ describe 'Problem', ->
describe 'when there is an exception', ->
beforeEach ->
@stubbedJax.root.toMathML.andThrow {restart: true}
error = new Error()
error.restart = true
@stubbedJax.root.toMathML.and.throwError error
@problem.updateMathML @stubbedJax, $('#input_example_1').get(0)
it 'should queue up the exception', ->
@@ -793,26 +833,29 @@ describe 'Problem', ->
matlabinput_html = readFixtures('matlabinput_problem.html')
beforeEach ->
spyOn($, 'postWithPrefix').andCallFake (url, callback) ->
spyOn($, 'postWithPrefix').and.callFake (url, callback) ->
callback html: matlabinput_html
jasmine.Clock.useMock()
jasmine.clock().install()
@problem = new Problem($('.xblock-student_view'))
spyOn(@problem, 'poll').andCallThrough()
spyOn(@problem, 'poll').and.callThrough()
@problem.render(matlabinput_html)
afterEach ->
jasmine.clock().uninstall()
it 'check that we stop polling after a fixed amount of time', ->
expect(@problem.poll).not.toHaveBeenCalled()
jasmine.Clock.tick(1)
jasmine.clock().tick(1)
time_steps = [1000, 2000, 4000, 8000, 16000, 32000]
num_calls = 1
for time_step in time_steps
do (time_step) =>
jasmine.Clock.tick(time_step)
expect(@problem.poll.callCount).toEqual(num_calls)
jasmine.clock().tick(time_step)
expect(@problem.poll.calls.count()).toEqual(num_calls)
num_calls += 1
# jump the next step and verify that we are not still continuing to poll
jasmine.Clock.tick(64000)
expect(@problem.poll.callCount).toEqual(6)
jasmine.clock().tick(64000)
expect(@problem.poll.calls.count()).toEqual(6)
expect($('.capa_alert').text()).toEqual("The grading process is still running. Refresh the page to see updates.")

View File

@@ -40,8 +40,8 @@
it('Default container initialized correctly', function () {
initialize(html);
expect(el.find('.shortform')).toContain('.full-top');
expect(el.find('.shortform')).toContain('.full-bottom');
expect(el.find('.shortform')).toContainElement('.full-top');
expect(el.find('.shortform')).toContainElement('.full-bottom');
expect(el.find('.longform')).toBeHidden();
expect(el.find('.full')).toHandle('click');
});
@@ -49,7 +49,7 @@
it('Custom container initialized correctly', function () {
initialize(html_custom);
expect(el.find('.shortform-custom')).toContain('.full-custom');
expect(el.find('.shortform-custom')).toContainElement('.full-custom');
expect(el.find('.full-custom')).toHaveText('Show shortform-custom');
expect(el.find('.longform')).toBeHidden();
expect(el.find('.full-custom')).toHandle('click');

View File

@@ -1,5 +1,6 @@
(function () {
'use strict';
var origAjax = $.ajax;
var stubbedYT = {
Player: function () {
@@ -15,9 +16,9 @@
]
);
Player.getDuration.andReturn(60);
Player.getAvailablePlaybackRates.andReturn([0.50, 1.0, 1.50, 2.0]);
Player.getAvailableQualityLevels.andReturn(
Player.getDuration.and.returnValue(60);
Player.getAvailablePlaybackRates.and.returnValue([0.50, 1.0, 1.50, 2.0]);
Player.getAvailableQualityLevels.and.returnValue(
['highres', 'hd1080', 'hd720', 'large', 'medium', 'small']
);
@@ -124,11 +125,11 @@
jasmine.stubRequests = function () {
var spy = $.ajax;
if (!($.ajax.isSpy)) {
if (!jasmine.isSpy($.ajax)) {
spy = spyOn($, 'ajax');
}
return spy.andCallFake(function (settings) {
return spy.and.callFake(function (settings) {
var match = settings.url
.match(/googleapis\.com\/.+\/videos\/\?id=(.+)&part=contentDetails/),
status, callCallback;
@@ -176,46 +177,16 @@
return;
} else if (settings.url === '/save_user_state') {
return {success: true};
} else if(settings.url.match(new RegExp(jasmine.getFixtures().fixturesPath + ".+", 'g'))) {
return origAjax(settings);
} else {
throw 'External request attempted for ' +
settings.url +
', which is not defined.';
$.ajax.and.callThrough();
}
});
};
// Add custom Jasmine matchers.
beforeEach(function () {
this.addMatchers({
toHaveAttrs: function (attrs) {
var element;
if ($.isEmptyObject(attrs)) {
return false;
}
element = this.actual;
return _.every(attrs, function (value, name) {
return element.attr(name) === value;
});
},
toBeInRange: function (min, max) {
return min <= this.actual && this.actual <= max;
},
toBeInArray: function (array) {
return $.inArray(this.actual, array) > -1;
},
toBeFocused: function () {
return $(this.actual)[0] === $(this.actual)[0].ownerDocument.activeElement;
}
});
return this.addMatchers(window.imagediff.jasmine);
});
// Stub jQuery.cookie module.
$.cookie = jasmine.createSpy('jQuery.cookie').andReturn('1.0');
// Stub jQuery.cookie module.
$.cookie = jasmine.createSpy('jQuery.cookie').and.returnValue('1.0');
// # Stub jQuery.qtip module.
$.fn.qtip = jasmine.createSpy('jQuery.qtip');
@@ -224,7 +195,7 @@
$.fn.scrollTo = jasmine.createSpy('jQuery.scrollTo');
// Stub window.Video.loadYouTubeIFrameAPI()
window.Video.loadYouTubeIFrameAPI = jasmine.createSpy('window.Video.loadYouTubeIFrameAPI').andReturn(
window.Video.loadYouTubeIFrameAPI = jasmine.createSpy('window.Video.loadYouTubeIFrameAPI').and.returnValue(
function (scriptTag) {
var event = document.createEvent('Event');
if (fixture === "video.html") {
@@ -275,13 +246,13 @@
],
obj = {},
delta = {
add: jasmine.createSpy().andReturn(obj),
substract: jasmine.createSpy().andReturn(obj),
reset: jasmine.createSpy().andReturn(obj)
add: jasmine.createSpy().and.returnValue(obj),
substract: jasmine.createSpy().and.returnValue(obj),
reset: jasmine.createSpy().and.returnValue(obj)
};
$.each(methods, function (index, method) {
obj[method] = jasmine.createSpy(method).andReturn(obj);
obj[method] = jasmine.createSpy(method).and.returnValue(obj);
});
obj.delta = delta;

View File

@@ -10,21 +10,21 @@ describe 'HTMLEditingDescriptor', ->
it 'Returns data from Visual Editor if text has changed', ->
visualEditorStub =
getContent: () -> 'from visual editor'
spyOn(@descriptor, 'getVisualEditor').andCallFake () ->
spyOn(@descriptor, 'getVisualEditor').and.callFake () ->
visualEditorStub
data = @descriptor.save().data
expect(data).toEqual('from visual editor')
it 'Returns data from Raw Editor if text has not changed', ->
visualEditorStub =
getContent: () -> '<p>original visual text</p>'
spyOn(@descriptor, 'getVisualEditor').andCallFake () ->
spyOn(@descriptor, 'getVisualEditor').and.callFake () ->
visualEditorStub
data = @descriptor.save().data
expect(data).toEqual('raw text')
it 'Performs link rewriting for static assets when saving', ->
visualEditorStub =
getContent: () -> 'from visual editor with /c4x/foo/bar/asset/image.jpg'
spyOn(@descriptor, 'getVisualEditor').andCallFake () ->
spyOn(@descriptor, 'getVisualEditor').and.callFake () ->
visualEditorStub
data = @descriptor.save().data
expect(data).toEqual('from visual editor with /static/image.jpg')

View File

@@ -1,11 +1,12 @@
(function(requirejs) {
requirejs.config({
baseUrl: '/base/',
paths: {
"moment": "xmodule/include/common_static/js/vendor/moment.min",
"modernizr": "xmodule/include/common_static/edx-pattern-library/js/modernizr-custom",
"afontgarde": "xmodule/include/common_static/edx-pattern-library/js/afontgarde",
"edxicons": "xmodule/include/common_static/edx-pattern-library/js/edx-icons",
"draggabilly": "xmodule/include/common_static/js/vendor/draggabilly"
"moment": "common_static/js/vendor/moment.min",
"modernizr": "common_static/edx-pattern-library/js/modernizr-custom",
"afontgarde": "common_static/edx-pattern-library/js/afontgarde",
"edxicons": "common_static/edx-pattern-library/js/edx-icons",
"draggabilly": "common_static/js/vendor/draggabilly"
},
"moment": {
exports: "moment"

View File

@@ -24,7 +24,7 @@ describe 'MarkdownEditingDescriptor', ->
it 'click on advanced editor should work', ->
loadFixtures 'problem-with-markdown.html'
@descriptor = new MarkdownEditingDescriptor($('.problem-editor'))
spyOn(@descriptor, 'confirmConversionToXml').andReturn(true)
spyOn(@descriptor, 'confirmConversionToXml').and.returnValue(true)
expect(@descriptor.confirmConversionToXml).not.toHaveBeenCalled()
e = jasmine.createSpyObj('e', [ 'preventDefault' ])
@descriptor.onShowXMLButton(e)

View File

@@ -14,8 +14,8 @@ describe "TabsEditingDescriptor", ->
TabsEditingDescriptor.Model.addModelUpdate(@html_id, 'Tab 1 Transcripts', @tab_1_modelUpdate)
TabsEditingDescriptor.Model.addOnSwitch(@html_id, 'Tab 1 Transcripts', @tab_1_switch)
spyOn($.fn, 'hide').andCallThrough()
spyOn($.fn, 'show').andCallThrough()
spyOn($.fn, 'hide').and.callThrough()
spyOn($.fn, 'show').and.callThrough()
spyOn(TabsEditingDescriptor.Model, 'initialize')
spyOn(TabsEditingDescriptor.Model, 'updateValue')
@@ -37,11 +37,11 @@ describe "TabsEditingDescriptor", ->
expect(@tab_1_switch).toHaveBeenCalled()
it "if click on current tab, nothing should happen", ->
spyOn($.fn, 'trigger').andCallThrough()
spyOn($.fn, 'trigger').and.callThrough()
currentTab = @descriptor.$tabs.filter('.' + @isCurrent)
@descriptor.$tabs.eq(0).trigger("click")
expect(@descriptor.$tabs.filter('.' + @isCurrent)).toEqual(currentTab)
expect($.fn.trigger.calls.length).toEqual(1)
expect($.fn.trigger.calls.count()).toEqual(1)
it "onSwitch function call", ->
@descriptor.$tabs.eq(1).trigger("click")
@@ -82,7 +82,7 @@ describe "TabsEditingDescriptor special save cases", ->
expect(data).toEqual(null)
it "case: no function in model update, but value presented", ->
@tab_0_modelUpdate = jasmine.createSpy('tab_0_modelUpdate').andReturn(1)
@tab_0_modelUpdate = jasmine.createSpy('tab_0_modelUpdate').and.returnValue(1)
TabsEditingDescriptor.Model.addModelUpdate(@html_id, 'Tab 0 Editor', @tab_0_modelUpdate)
@descriptor.$tabs.eq(1).trigger("click")
expect(@tab_0_modelUpdate).toHaveBeenCalled()

View File

@@ -15,82 +15,66 @@ function (AsyncProcess) {
items = getArrayNthLength(1000);
describe('AsyncProcess', function () {
it ('Array is processed successfully', function () {
it ('Array is processed successfully', function (done) {
var processedArray,
expectedArray = getArrayNthLength(1000, 2),
process = function (item) {
return 2 * item;
};
runs(function () {
AsyncProcess.array(items, process).done(function (result) {
processedArray = result;
});
AsyncProcess.array(items, process).done(function (result) {
processedArray = result;
});
waitsFor(function () {
jasmine.waitUntil(function () {
return processedArray;
}, 'Array processing takes too much time', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expect(processedArray).toEqual(expectedArray);
});
}).always(done);
});
it ('If non-array is passed, error callback is called', function () {
it ('If non-array is passed, error callback is called', function (done) {
var isError,
process = function () {};
runs(function () {
AsyncProcess.array('string', process).fail(function () {
isError = true;
});
AsyncProcess.array('string', process).fail(function () {
isError = true;
});
waitsFor(function () {
jasmine.waitUntil(function () {
return isError;
}, 'Error callback wasn\'t called', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expect(isError).toBeTruthy();
});
}).always(done);
});
it ('If an empty array is passed, returns initial array', function () {
it ('If an empty array is passed, returns initial array', function (done) {
var processedArray,
process = function () {};
runs(function () {
AsyncProcess.array([], process).done(function (result) {
processedArray = result;
});
AsyncProcess.array([], process).done(function (result) {
processedArray = result;
});
waitsFor(function () {
jasmine.waitUntil(function () {
return processedArray;
}, 'Array processing takes too much time', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expect(processedArray).toEqual([]);
});
}).always(done);
});
it ('If no process function passed, returns initial array', function () {
it ('If no process function passed, returns initial array', function (done) {
var processedArray;
runs(function () {
AsyncProcess.array(items).done(function (result) {
processedArray = result;
});
AsyncProcess.array(items).done(function (result) {
processedArray = result;
});
waitsFor(function () {
jasmine.waitUntil(function () {
return processedArray;
}, 'Array processing takes too much time', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expect(processedArray).toEqual(items);
});
}).always(done);
});
});
});

View File

@@ -7,9 +7,7 @@
oldOTBD = window.onTouchBasedDevice;
window.onTouchBasedDevice = jasmine
.createSpy('onTouchBasedDevice')
.andReturn(null);
jasmine.stubRequests();
.and.returnValue(null);
state = jasmine.initializePlayer();
@@ -20,26 +18,23 @@
$('source').remove();
window.onTouchBasedDevice = oldOTBD;
state.storage.clear();
state.videoPlayer.destroy();
});
it('initialize', function () {
waitsFor(function () {
it('initialize', function (done) {
jasmine.waitUntil(function () {
return state.el.hasClass('is-initialized');
}, 'Player is not initialized.', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expect('initialize').not.toHaveBeenTriggeredOn('.video');
});
}).always(done);
});
it('ready', function () {
waitsFor(function () {
it('ready', function (done) {
jasmine.waitUntil(function () {
return state.el.hasClass('is-initialized');
}, 'Player is not initialized.', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expect('ready').not.toHaveBeenTriggeredOn('.video');
});
}).always(done);
});
it('play', function () {
@@ -86,9 +81,7 @@
oldOTBD = window.onTouchBasedDevice;
window.onTouchBasedDevice = jasmine
.createSpy('onTouchBasedDevice')
.andReturn(null);
jasmine.stubRequests();
.and.returnValue(null);
state = jasmine.initializePlayerYouTube();
});
@@ -96,6 +89,8 @@
afterEach(function () {
$('source').remove();
window.onTouchBasedDevice = oldOTBD;
state.storage.clear();
state.videoPlayer.destroy();
});
it('qualitychange', function () {

View File

@@ -2,26 +2,27 @@
describe('Video', function () {
var oldOTBD, state;
beforeEach(function () {
jasmine.stubRequests();
});
afterEach(function () {
$('source').remove();
window.VideoState = {};
window.VideoState.id = {};
window.YT = jasmine.YT;
});
describe('constructor', function () {
describe('YT', function () {
beforeEach(function () {
loadFixtures('video.html');
$.cookie.andReturn('0.50');
this.state = jasmine.initializePlayerYouTube('video_html5.html');
$.cookie.and.returnValue('0.50');
});
describe('by default', function () {
beforeEach(function () {
this.state = jasmine.initializePlayerYouTube('video_html5.html');
});
afterEach(function () {
this.state.storage.clear();
this.state.videoPlayer.destroy();
});
@@ -30,7 +31,7 @@
});
it('set the elements', function () {
expect(this.state.el).toBe('#video_id');
expect(this.state.el).toEqual($('#video_id'));
});
it('parse the videos', function () {
@@ -55,13 +56,13 @@
var state;
beforeEach(function () {
$.cookie.andReturn('0.75');
$.cookie.and.returnValue('0.75');
state = jasmine.initializePlayer('video_html5.html');
});
afterEach(function () {
state.storage.clear();
state.videoPlayer.destroy();
state = undefined;
});
describe('by default', function () {
@@ -70,7 +71,7 @@
});
it('set the elements', function () {
expect(state.el).toBe('#video_id');
expect(state.el).toEqual($('#video_id'));
});
it('doesn\'t have `videos` dictionary', function () {
@@ -101,35 +102,34 @@
});
describe('YouTube API is not loaded', function () {
var state;
beforeEach(function () {
window.YT = undefined;
state = jasmine.initializePlayerYouTube();
})
});
afterEach(function () {
state.storage.clear();
state.videoPlayer.destroy();
});
it('callback, to be called after YouTube API loads, exists and is called', function () {
waitsFor(function () {
return state.youtubeApiAvailable === true;
}, 'YouTube API is loaded', 3000);
it('callback, to be called after YouTube API loads, exists and is called', function (done) {
window.YT = jasmine.YT;
// Call the callback that must be called when YouTube API is
// loaded. By specification.
window.onYouTubeIframeAPIReady();
runs(function () {
jasmine.waitUntil(function () {
return state.youtubeApiAvailable === true;
}).done(function(){
// If YouTube API is not loaded, then the code will should create
// a global callback that will be called by API once it is loaded.
expect(window.onYouTubeIframeAPIReady).not.toBeUndefined();
});
}).always(done);
});
});
describe('checking start and end times', function () {
var state;
var miniTestSuite = [
{
itDescription: 'both times are proper',
@@ -159,6 +159,7 @@
];
afterEach(function () {
state.storage.clear();
state.videoPlayer.destroy();
});

View File

@@ -1,17 +1,19 @@
(function (undefined) {
describe('Video HTML5Video', function () {
var STATUS = window.STATUS;
var state, oldOTBD, playbackRates = [0.75, 1.0, 1.25, 1.5];
beforeEach(function () {
oldOTBD = window.onTouchBasedDevice;
window.onTouchBasedDevice = jasmine
.createSpy('onTouchBasedDevice').andReturn(null);
.createSpy('onTouchBasedDevice').and.returnValue(null);
});
afterEach(function () {
state.storage.clear();
state.videoPlayer.destroy();
$.fn.scrollTo.reset();
$.fn.scrollTo.calls.reset();
$('source').remove();
window.onTouchBasedDevice = oldOTBD;
});
@@ -25,13 +27,13 @@
describe('events:', function () {
beforeEach(function () {
spyOn(state.videoPlayer.player, 'callStateChangeCallback').andCallThrough();
spyOn(state.videoPlayer.player, 'callStateChangeCallback').and.callThrough();
});
describe('[click]', function () {
describe('when player is paused', function () {
beforeEach(function () {
spyOn(state.videoPlayer.player.video, 'play').andCallThrough();
spyOn(state.videoPlayer.player.video, 'play').and.callThrough();
state.videoPlayer.player.playerState = STATUS.PAUSED;
$(state.videoPlayer.player.videoEl).trigger('click');
});
@@ -40,32 +42,25 @@
expect(state.videoPlayer.player.video.play).toHaveBeenCalled();
});
it('player state was changed', function () {
waitsFor(function () {
return state.videoPlayer.player.getPlayerState() !== STATUS.PAUSED;
}, 'Player state should be changed', WAIT_TIMEOUT);
runs(function () {
expect(state.videoPlayer.player.getPlayerState())
.toBe(STATUS.PLAYING);
});
it('player state was changed', function (done) {
jasmine.waitUntil(function () {
return state.videoPlayer.player.getPlayerState() === STATUS.PLAYING;
}).always(done);
});
it('callback was not called', function () {
waitsFor(function () {
// Flaky. Checking the parameters of calls to onStateChange() will likely be more reliable.
xit('callback was not called', function (done) {
jasmine.waitUntil(function () {
return state.videoPlayer.player.getPlayerState() !== STATUS.PAUSED;
}, 'Player state should be changed', WAIT_TIMEOUT);
runs(function () {
expect(state.videoPlayer.player.callStateChangeCallback)
.not.toHaveBeenCalled();
});
}).then(function () {
expect(state.videoPlayer.player.callStateChangeCallback).not.toHaveBeenCalled();
}).always(done);
});
});
describe('[player is playing]', function () {
beforeEach(function () {
spyOn(state.videoPlayer.player.video, 'pause').andCallThrough();
spyOn(state.videoPlayer.player.video, 'pause').and.callThrough();
state.videoPlayer.player.playerState = STATUS.PLAYING;
$(state.videoPlayer.player.videoEl).trigger('click');
});
@@ -74,33 +69,29 @@
expect(state.videoPlayer.player.video.pause).toHaveBeenCalled();
});
it('player state was changed', function () {
waitsFor(function () {
it('player state was changed', function (done) {
jasmine.waitUntil(function () {
return state.videoPlayer.player.getPlayerState() !== STATUS.PLAYING;
}, 'Player state should be changed', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expect(state.videoPlayer.player.getPlayerState())
.toBe(STATUS.PAUSED);
});
}).always(done);
});
it('callback was not called', function () {
waitsFor(function () {
it('callback was not called', function (done) {
jasmine.waitUntil(function () {
return state.videoPlayer.player.getPlayerState() !== STATUS.PLAYING;
}, 'Player state should be changed', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expect(state.videoPlayer.player.callStateChangeCallback)
.not.toHaveBeenCalled();
});
}).always(done);
});
});
});
describe('[play]', function () {
beforeEach(function () {
spyOn(state.videoPlayer.player.video, 'play').andCallThrough();
spyOn(state.videoPlayer.player.video, 'play').and.callThrough();
state.videoPlayer.player.playerState = STATUS.PAUSED;
state.videoPlayer.player.playVideo();
});
@@ -110,37 +101,35 @@
});
it('player state was changed', function () {
waitsFor(function () {
it('player state was changed', function (done) {
jasmine.waitUntil(function () {
return state.videoPlayer.player.getPlayerState() !== STATUS.PAUSED;
}, 'Player state should be changed', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expect(state.videoPlayer.player.getPlayerState())
.toBe(STATUS.BUFFERING);
});
}).always(done);
});
it('callback was called', function () {
waitsFor(function () {
it('callback was called', function (done) {
jasmine.waitUntil(function () {
return state.videoPlayer.player.getPlayerState() !== STATUS.PAUSED;
}, 'Player state should be changed', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expect(state.videoPlayer.player.callStateChangeCallback)
.toHaveBeenCalled();
});
}).always(done);
});
});
describe('[pause]', function () {
beforeEach(function () {
spyOn(state.videoPlayer.player.video, 'pause').andCallThrough();
beforeEach(function (done) {
spyOn(state.videoPlayer.player.video, 'pause').and.callThrough();
state.videoPlayer.player.playerState = STATUS.UNSTARTED;
state.videoPlayer.player.playVideo();
waitsFor(function () {
jasmine.waitUntil(function () {
return state.videoPlayer.player.getPlayerState() !== STATUS.UNSTARTED;
}, 'Video never started playing', WAIT_TIMEOUT);
}).done(done);
state.videoPlayer.player.pauseVideo();
});
@@ -148,59 +137,54 @@
expect(state.videoPlayer.player.video.pause).toHaveBeenCalled();
});
it('player state was changed', function () {
waitsFor(function () {
it('player state was changed', function (done) {
jasmine.waitUntil(function () {
return state.videoPlayer.player.getPlayerState() !== STATUS.PLAYING;
}, 'Player state should be changed', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expect(state.videoPlayer.player.getPlayerState())
.toBe(STATUS.PAUSED);
});
}).always(done);
});
it('callback was called', function () {
waitsFor(function () {
it('callback was called', function (done) {
jasmine.waitUntil(function () {
return state.videoPlayer.player.getPlayerState() !== STATUS.PLAYING;
}, 'Player state should be changed', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expect(state.videoPlayer.player.callStateChangeCallback)
.toHaveBeenCalled();
});
}).always(done);
});
});
describe('[loadedmetadata]', function () {
it(
'player state was changed, start/end was defined, ' +
'onReady called', function ()
'onReady called', function (done)
{
waitsFor(function () {
jasmine.fireEvent(state.videoPlayer.player.video, 'loadedmetadata');
jasmine.waitUntil(function () {
return state.videoPlayer.player.getPlayerState() !== STATUS.UNSTARTED;
}, 'Video cannot be played', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expect(state.videoPlayer.player.getPlayerState())
.toBe(STATUS.PAUSED);
expect(state.videoPlayer.player.video.currentTime).toBe(0);
expect(state.videoPlayer.player.config.events.onReady)
.toHaveBeenCalled();
});
}).always(done);
});
});
describe('[ended]', function () {
beforeEach(function () {
waitsFor(function () {
beforeEach(function (done) {
state.videoPlayer.player.playVideo();
jasmine.waitUntil(function () {
return state.videoPlayer.player.getPlayerState() !== STATUS.UNSTARTED;
}, 'Video cannot be played', WAIT_TIMEOUT);
}).done(done);
});
it('player state was changed', function () {
runs(function () {
jasmine.fireEvent(state.videoPlayer.player.video, 'ended');
expect(state.videoPlayer.player.getPlayerState()).toBe(STATUS.ENDED);
});
jasmine.fireEvent(state.videoPlayer.player.video, 'ended');
expect(state.videoPlayer.player.getPlayerState()).toBe(STATUS.ENDED);
});
it('callback was called', function () {
@@ -215,98 +199,90 @@
var volume, seek, duration, playbackRate;
beforeEach(function () {
waitsFor(function () {
volume = state.videoPlayer.player.video.volume;
seek = state.videoPlayer.player.video.currentTime;
return state.videoPlayer.player.playerState === STATUS.PAUSED;
}, 'Video cannot be played', WAIT_TIMEOUT);
volume = state.videoPlayer.player.video.volume;
});
it('pauseVideo', function () {
runs(function () {
spyOn(state.videoPlayer.player.video, 'pause').andCallThrough();
state.videoPlayer.player.pauseVideo();
expect(state.videoPlayer.player.video.pause).toHaveBeenCalled();
});
spyOn(state.videoPlayer.player.video, 'pause').and.callThrough();
state.videoPlayer.player.pauseVideo();
expect(state.videoPlayer.player.video.pause).toHaveBeenCalled();
});
describe('seekTo', function () {
it('set new correct value', function () {
runs(function () {
it('set new correct value', function (done) {
state.videoPlayer.player.playVideo();
jasmine.waitUntil(function () {
return state.videoPlayer.player.getPlayerState() === STATUS.PLAYING;
}).then(function() {
state.videoPlayer.player.seekTo(2);
expect(state.videoPlayer.player.getCurrentTime()).toBe(2);
});
}).done(done);
});
it('set new inccorrect values', function () {
runs(function () {
state.videoPlayer.player.seekTo(-50);
expect(state.videoPlayer.player.getCurrentTime()).toBe(seek);
state.videoPlayer.player.seekTo('5');
expect(state.videoPlayer.player.getCurrentTime()).toBe(seek);
state.videoPlayer.player.seekTo(500000);
expect(state.videoPlayer.player.getCurrentTime()).toBe(seek);
});
var seek = state.videoPlayer.player.video.currentTime;
state.videoPlayer.player.seekTo(-50);
expect(state.videoPlayer.player.getCurrentTime()).toBe(seek);
state.videoPlayer.player.seekTo('5');
expect(state.videoPlayer.player.getCurrentTime()).toBe(seek);
state.videoPlayer.player.seekTo(500000);
expect(state.videoPlayer.player.getCurrentTime()).toBe(seek);
});
});
describe('setVolume', function () {
it('set new correct value', function () {
runs(function () {
state.videoPlayer.player.setVolume(50);
expect(state.videoPlayer.player.getVolume()).toBe(50 * 0.01);
});
state.videoPlayer.player.setVolume(50);
expect(state.videoPlayer.player.getVolume()).toBe(50 * 0.01);
});
it('set new incorrect values', function () {
runs(function () {
state.videoPlayer.player.setVolume(-50);
expect(state.videoPlayer.player.getVolume()).toBe(volume);
state.videoPlayer.player.setVolume('5');
expect(state.videoPlayer.player.getVolume()).toBe(volume);
state.videoPlayer.player.setVolume(500000);
expect(state.videoPlayer.player.getVolume()).toBe(volume);
});
});
});
it('getCurrentTime', function () {
runs(function () {
state.videoPlayer.player.video.currentTime = 3;
expect(state.videoPlayer.player.getCurrentTime())
.toBe(state.videoPlayer.player.video.currentTime);
});
});
it('playVideo', function () {
runs(function () {
spyOn(state.videoPlayer.player.video, 'play').andCallThrough();
state.videoPlayer.player.playVideo();
expect(state.videoPlayer.player.video.play).toHaveBeenCalled();
});
});
it('getPlayerState', function () {
runs(function () {
state.videoPlayer.player.playerState = STATUS.PLAYING;
expect(state.videoPlayer.player.getPlayerState()).toBe(STATUS.PLAYING);
state.videoPlayer.player.playerState = STATUS.ENDED;
expect(state.videoPlayer.player.getPlayerState()).toBe(STATUS.ENDED);
});
});
it('getVolume', function () {
runs(function () {
volume = state.videoPlayer.player.video.volume = 0.5;
state.videoPlayer.player.setVolume(-50);
expect(state.videoPlayer.player.getVolume()).toBe(volume);
state.videoPlayer.player.setVolume('5');
expect(state.videoPlayer.player.getVolume()).toBe(volume);
state.videoPlayer.player.setVolume(500000);
expect(state.videoPlayer.player.getVolume()).toBe(volume);
});
});
it('getDuration', function () {
runs(function () {
it('getCurrentTime', function (done) {
state.videoPlayer.player.playVideo();
jasmine.waitUntil(function () {
return state.videoPlayer.player.getPlayerState() === STATUS.PLAYING;
}).then(function() {
state.videoPlayer.player.video.currentTime = 3;
expect(state.videoPlayer.player.getCurrentTime())
.toBe(state.videoPlayer.player.video.currentTime);
}).done(done);
});
it('playVideo', function () {
spyOn(state.videoPlayer.player.video, 'play').and.callThrough();
state.videoPlayer.player.playVideo();
expect(state.videoPlayer.player.video.play).toHaveBeenCalled();
});
it('getPlayerState', function () {
state.videoPlayer.player.playerState = STATUS.PLAYING;
expect(state.videoPlayer.player.getPlayerState()).toBe(STATUS.PLAYING);
state.videoPlayer.player.playerState = STATUS.ENDED;
expect(state.videoPlayer.player.getPlayerState()).toBe(STATUS.ENDED);
});
it('getVolume', function () {
volume = state.videoPlayer.player.video.volume = 0.5;
expect(state.videoPlayer.player.getVolume()).toBe(volume);
});
it('getDuration', function (done) {
state.videoPlayer.player.playVideo();
jasmine.waitUntil(function () {
return state.videoPlayer.player.getPlayerState() === STATUS.PLAYING;
}).then(function () {
duration = state.videoPlayer.player.video.duration;
expect(state.videoPlayer.player.getDuration()).toBe(duration);
});
}).always(done);
});
describe('setPlaybackRate', function () {
@@ -333,18 +309,21 @@
.toEqual(playbackRates);
});
it('_getLogs', function () {
runs(function () {
it('_getLogs', function (done) {
state.videoPlayer.player.playVideo();
jasmine.waitUntil(function () {
return state.videoPlayer.player.getPlayerState() === STATUS.PLAYING;
}).then(function() {
var logs = state.videoPlayer.player._getLogs();
expect(logs).toEqual(jasmine.any(Array));
expect(logs.length).toBeGreaterThan(0);
});
}).done(done);
});
});
});
it('native controls are used on iPhone', function () {
window.onTouchBasedDevice.andReturn(['iPhone']);
window.onTouchBasedDevice.and.returnValue(['iPhone']);
state = jasmine.initializePlayer('video_html5.html');

View File

@@ -82,7 +82,7 @@ function (Initialize) {
'1.50': 'videoId'
},
youtubeId: Initialize.prototype.youtubeId,
isFlashMode: jasmine.createSpy().andReturn(false)
isFlashMode: jasmine.createSpy().and.returnValue(false)
};
});
@@ -100,7 +100,7 @@ function (Initialize) {
it('returns duration for current video', function () {
var expected;
state.isFlashMode.andReturn(true);
state.isFlashMode.and.returnValue(true);
expected = Initialize.prototype.getDuration.call(state);
expect(expected).toEqual(100);
@@ -110,7 +110,7 @@ function (Initialize) {
it(msg, function () {
var expected;
state.isFlashMode.andReturn(true);
state.isFlashMode.and.returnValue(true);
state.speed = '2.0';
expected = Initialize.prototype.getDuration.call(state);
@@ -128,7 +128,7 @@ function (Initialize) {
'1.0': 'cogebirgzzM',
'1.50': 'abcdefghijkl'
},
isFlashMode: jasmine.createSpy().andReturn(false)
isFlashMode: jasmine.createSpy().and.returnValue(false)
};
});
@@ -148,7 +148,7 @@ function (Initialize) {
it('return the video id for current speed', function () {
var expected;
state.isFlashMode.andReturn(true);
state.isFlashMode.and.returnValue(true);
expected = Initialize.prototype.youtubeId.call(state);
expect(expected).toEqual('abcdefghijkl');
@@ -279,7 +279,7 @@ function (Initialize) {
describe('isFlashMode', function () {
it('returns `true` if player in `flash` mode', function () {
var state = {
getPlayerMode: jasmine.createSpy().andReturn('flash'),
getPlayerMode: jasmine.createSpy().and.returnValue('flash'),
},
isFlashMode = Initialize.prototype.isFlashMode,
actual = isFlashMode.call(state);
@@ -289,7 +289,7 @@ function (Initialize) {
it('returns `false` if player is not in `flash` mode', function () {
var state = {
getPlayerMode: jasmine.createSpy().andReturn('html5'),
getPlayerMode: jasmine.createSpy().and.returnValue('html5'),
},
isFlashMode = Initialize.prototype.isFlashMode,
actual = isFlashMode.call(state);
@@ -301,7 +301,7 @@ function (Initialize) {
describe('isHtml5Mode', function () {
it('returns `true` if player in `html5` mode', function () {
var state = {
getPlayerMode: jasmine.createSpy().andReturn('html5'),
getPlayerMode: jasmine.createSpy().and.returnValue('html5'),
},
isHtml5Mode = Initialize.prototype.isHtml5Mode,
actual = isHtml5Mode.call(state);
@@ -311,7 +311,7 @@ function (Initialize) {
it('returns `false` if player is not in `html5` mode', function () {
var state = {
getPlayerMode: jasmine.createSpy().andReturn('flash'),
getPlayerMode: jasmine.createSpy().and.returnValue('flash'),
},
isHtml5Mode = Initialize.prototype.isHtml5Mode,
actual = isHtml5Mode.call(state);

View File

@@ -139,7 +139,7 @@ function (Resizer) {
.align()
.alignByHeightOnly();
expect(spiesList[0].calls.length).toEqual(1);
expect(spiesList[0].calls.count()).toEqual(1);
});
it('all callbacks are removed', function () {
@@ -180,7 +180,7 @@ function (Resizer) {
resizer.callbacks[methodName](arg);
expect(console.error).toHaveBeenCalledWith(errorMessage);
//reset spy
console.log.reset();
console.log.calls.reset();
});
});

View File

@@ -101,7 +101,7 @@
menuList = container.children('ol.a11y-menu-list');
menuItems = menuList.children('li.a11y-menu-item');
menuItemsLinks = menuItems.children('a.a11y-menu-item-link');
spyOn($.fn, 'focus').andCallThrough();
spyOn($.fn, 'focus').and.callThrough();
});
it('open/close the menu on mouseenter/mouseleave', function () {
@@ -173,7 +173,7 @@
}
// Test if each element has been called twice.
expect($.fn.focus.calls.length)
expect($.fn.focus.calls.count())
.toEqual(2*menuItemsLinks.length+1);
});
@@ -258,7 +258,7 @@
beforeEach(function () {
state = jasmine.initializePlayer();
state.videoSpeedControl.setSpeed(1.0);
spyOn(state.videoPlayer, 'onSpeedChange').andCallThrough();
spyOn(state.videoPlayer, 'onSpeedChange').and.callThrough();
$('li[data-speed="0.75"] .speed-link').click();
});

View File

@@ -1,21 +1,21 @@
(function (WAIT_TIMEOUT) {
'use strict';
describe('VideoBumper', function () {
xdescribe('VideoBumper', function () {
var state, oldOTBD, waitForPlaying;
waitForPlaying = function (state) {
waitsFor(function () {
waitForPlaying = function (state, done) {
jasmine.waitUntil(function () {
return state.el.hasClass('is-playing');
}, 'Player is not playing.', WAIT_TIMEOUT);
}).done(done);
};
beforeEach(function () {
oldOTBD = window.onTouchBasedDevice;
window.onTouchBasedDevice = jasmine
.createSpy('onTouchBasedDevice').andReturn(null);
.createSpy('onTouchBasedDevice').and.returnValue(null);
state = jasmine.initializePlayer('video_with_bumper.html');
$('.poster .btn-play').click();
jasmine.Clock.useMock();
jasmine.clock().install();
});
afterEach(function () {
@@ -28,45 +28,46 @@
state.videoPlayer.destroy();
}
window.onTouchBasedDevice = oldOTBD;
jasmine.clock().uninstall();
});
it('can render the bumper video', function () {
expect($('.is-bumper')).toExist();
});
it('can show the main video on error', function () {
it('can show the main video on error', function (done) {
state.el.trigger('error');
jasmine.Clock.tick(20);
jasmine.clock().tick(20);
expect($('.is-bumper')).not.toExist();
waitForPlaying(state);
waitForPlaying(state, done);
});
it('can show the main video once bumper ends', function () {
it('can show the main video once bumper ends', function (done) {
state.el.trigger('ended');
jasmine.Clock.tick(20);
jasmine.clock().tick(20);
expect($('.is-bumper')).not.toExist();
waitForPlaying(state);
waitForPlaying(state, done);
});
it('can show the main video on skip', function () {
it('can show the main video on skip', function (done) {
state.bumperState.videoBumper.skip();
jasmine.Clock.tick(20);
jasmine.clock().tick(20);
expect($('.is-bumper')).not.toExist();
waitForPlaying(state);
waitForPlaying(state, done);
});
it('can stop the bumper video playing if it is too long', function () {
it('can stop the bumper video playing if it is too long', function (done) {
state.el.trigger('timeupdate', [state.bumperState.videoBumper.maxBumperDuration + 1]);
jasmine.Clock.tick(20);
jasmine.clock().tick(20);
expect($('.is-bumper')).not.toExist();
waitForPlaying(state);
waitForPlaying(state, done);
});
it('can save appropriate states correctly on ended', function () {
var saveState = jasmine.createSpy('saveState');
state.bumperState.videoSaveStatePlugin.saveState = saveState;
state.el.trigger('ended');
jasmine.Clock.tick(20);
jasmine.clock().tick(20);
expect(saveState).toHaveBeenCalledWith(true, {
bumper_last_view_date: true});
});
@@ -76,7 +77,7 @@
state.bumperState.videoSaveStatePlugin.saveState = saveState;
state.bumperState.videoBumper.skip();
expect(state.storage.getItem('isBumperShown')).toBeTruthy();
jasmine.Clock.tick(20);
jasmine.clock().tick(20);
expect(saveState).toHaveBeenCalledWith(true, {
bumper_last_view_date: true});
});
@@ -86,7 +87,7 @@
state.bumperState.videoSaveStatePlugin.saveState = saveState;
state.el.trigger('error');
expect(state.storage.getItem('isBumperShown')).toBeTruthy();
jasmine.Clock.tick(20);
jasmine.clock().tick(20);
expect(saveState).toHaveBeenCalledWith(true, {
bumper_last_view_date: true});
});
@@ -96,7 +97,7 @@
state.bumperState.videoSaveStatePlugin.saveState = saveState;
state.bumperState.videoBumper.skipAndDoNotShowAgain();
expect(state.storage.getItem('isBumperShown')).toBeTruthy();
jasmine.Clock.tick(20);
jasmine.clock().tick(20);
expect(saveState).toHaveBeenCalledWith(true, {
bumper_last_view_date: true, bumper_do_not_show_again: true});
});

View File

@@ -1,13 +1,16 @@
(function (undefined) {
describe('VideoCaption', function () {
var state, oldOTBD;
var parseIntAttribute = function (element, attrName) {
return parseInt(element.attr(attrName));
};
beforeEach(function () {
oldOTBD = window.onTouchBasedDevice;
window.onTouchBasedDevice = jasmine.createSpy('onTouchBasedDevice')
.andReturn(null);
.and.returnValue(null);
$.fn.scrollTo.reset();
$.fn.scrollTo.calls.reset();
});
afterEach(function () {
@@ -15,7 +18,7 @@
// had before. Removing of `source` tag, not `video` tag, stops
// loading video source and clears the memory.
$('source').remove();
$.fn.scrollTo.reset();
$.fn.scrollTo.calls.reset();
state.storage.clear();
state.videoPlayer.destroy();
@@ -27,17 +30,17 @@
describe('always', function () {
beforeEach(function () {
spyOn($, 'ajaxWithPrefix').andCallThrough();
spyOn($, 'ajaxWithPrefix').and.callThrough();
});
it('create the transcript element', function () {
state = jasmine.initializePlayer();
expect($('.video')).toContain('.subtitles');
expect($('.video')).toContainElement('.subtitles');
});
it('add transcript control to video player', function () {
state = jasmine.initializePlayer();
expect($('.video')).toContain('.toggle-transcript');
expect($('.video')).toContainElement('.toggle-transcript');
});
it('add ARIA attributes to transcript control', function () {
@@ -50,20 +53,16 @@
it('adds the captioning control to the video player', function() {
state = jasmine.initializePlayer();
expect($('.video')).toContain('.toggle-captions');
expect($('.video')).toContain('.closed-captions');
expect($('.video')).toContainElement('.toggle-captions');
expect($('.video')).toContainElement('.closed-captions');
});
it('fetch the transcript in HTML5 mode', function () {
runs(function () {
state = jasmine.initializePlayer();
});
it('fetch the transcript in HTML5 mode', function (done) {
state = jasmine.initializePlayer();
waitsFor(function () {
jasmine.waitUntil(function () {
return state.videoCaption.loaded;
}, 'Expect transcript to be loaded.', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expect($.ajaxWithPrefix).toHaveBeenCalledWith({
url: '/transcript/translation/en',
notifyOnError: false,
@@ -71,23 +70,19 @@
success: jasmine.any(Function),
error: jasmine.any(Function)
});
expect($.ajaxWithPrefix.mostRecentCall.args[0].data)
expect($.ajaxWithPrefix.calls.mostRecent().args[0].data)
.toBeUndefined();
});
}).always(done);
});
it('fetch the transcript in Flash mode', function () {
runs(function () {
state = jasmine.initializePlayerYouTube();
spyOn(state, 'isFlashMode').andReturn(true);
state.videoCaption.fetchCaption();
});
it('fetch the transcript in Flash mode', function (done) {
state = jasmine.initializePlayerYouTube();
spyOn(state, 'isFlashMode').and.returnValue(true);
state.videoCaption.fetchCaption();
waitsFor(function () {
jasmine.waitUntil(function () {
return state.videoCaption.loaded;
}, 'Expect transcript to be loaded.', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expect($.ajaxWithPrefix).toHaveBeenCalledWith({
url: '/transcript/translation/en',
notifyOnError: false,
@@ -95,23 +90,19 @@
success: jasmine.any(Function),
error: jasmine.any(Function)
});
expect($.ajaxWithPrefix.mostRecentCall.args[0].data)
expect($.ajaxWithPrefix.calls.mostRecent().args[0].data)
.toEqual({
videoId: 'cogebirgzzM'
});
});
}).always(done);
});
it('fetch the transcript in Youtube mode', function () {
runs(function () {
state = jasmine.initializePlayerYouTube();
});
it('fetch the transcript in Youtube mode', function (done) {
state = jasmine.initializePlayerYouTube();
waitsFor(function () {
jasmine.waitUntil(function () {
return state.videoCaption.loaded;
}, 'Expect transcript to be loaded.', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expect($.ajaxWithPrefix).toHaveBeenCalledWith({
url: '/transcript/translation/en',
notifyOnError: false,
@@ -119,11 +110,11 @@
success: jasmine.any(Function),
error: jasmine.any(Function)
});
expect($.ajaxWithPrefix.mostRecentCall.args[0].data)
expect($.ajaxWithPrefix.calls.mostRecent().args[0].data)
.toEqual({
videoId: 'cogebirgzzM'
});
});
}).always(done);
});
it('bind the mouse movement', function () {
@@ -148,7 +139,7 @@
state = jasmine.initializePlayer();
var plugin = state.videoCaption;
spyOn($.fn, 'off').andCallThrough();
spyOn($.fn, 'off').and.callThrough();
state.videoCaption.destroy();
expect(state.videoCaption).toBeUndefined();
@@ -316,104 +307,90 @@
});
describe('when on a non touch-based device', function () {
beforeEach(function () {
runs(function () {
state = jasmine.initializePlayer();
});
beforeEach(function (done) {
state = jasmine.initializePlayer();
waitsFor(function () {
jasmine.waitUntil(function () {
return state.videoCaption.rendered;
}, 'Transcripts are not rendered', WAIT_TIMEOUT);
}).then(done);
});
it('render the transcript', function () {
runs(function () {
var captionsData = jasmine.stubbedCaption,
items = $('.subtitles li[data-index]');
var captionsData = jasmine.stubbedCaption,
items = $('.subtitles li[data-index]');
_.each(captionsData.text, function (text, index) {
var item = items.eq(index);
_.each(captionsData.text, function (text, index) {
var item = items.eq(index);
expect(item).toHaveData('index', index);
expect(item).toHaveData(
'start', captionsData.start[index]
);
expect(item).toHaveAttr('tabindex', 0);
expect(item).toHaveText(text);
});
expect(parseIntAttribute(item, 'data-index')).toEqual(index);
expect(parseIntAttribute(item, 'data-start')).toEqual(captionsData.start[index]);
expect(item.attr('tabindex')).toEqual(0);
expect(item.text().trim()).toEqual(captionsData.text[index]);
});
});
it('add a padding element to transcript', function () {
runs(function () {
expect($('.subtitles li:first').hasClass('spacing'))
.toBe(true);
expect($('.subtitles li:last').hasClass('spacing'))
.toBe(true);
});
expect($('.subtitles li:first').hasClass('spacing'))
.toBe(true);
expect($('.subtitles li:last').hasClass('spacing'))
.toBe(true);
});
it('bind all the transcript link', function () {
runs(function () {
var handlerList = ['captionMouseOverOut', 'captionClick',
'captionMouseDown', 'captionFocus', 'captionBlur',
'captionKeyDown'
];
var handlerList = ['captionMouseOverOut', 'captionClick',
'captionMouseDown', 'captionFocus', 'captionBlur',
'captionKeyDown'
];
$.each(handlerList, function(index, handler) {
spyOn(state.videoCaption, handler);
});
$('.subtitles li[data-index]').each(
function (index, link) {
$.each(handlerList, function(index, handler) {
spyOn(state.videoCaption, handler);
});
$('.subtitles li[data-index]').each(
function (index, link) {
$(link).trigger('mouseover');
expect(state.videoCaption.captionMouseOverOut).toHaveBeenCalled();
$(link).trigger('mouseover');
expect(state.videoCaption.captionMouseOverOut).toHaveBeenCalled();
state.videoCaption.captionMouseOverOut.reset();
$(link).trigger('mouseout');
expect(state.videoCaption.captionMouseOverOut).toHaveBeenCalled();
state.videoCaption.captionMouseOverOut.calls.reset();
$(link).trigger('mouseout');
expect(state.videoCaption.captionMouseOverOut).toHaveBeenCalled();
$(this).click();
expect(state.videoCaption.captionClick).toHaveBeenCalled();
$(this).click();
expect(state.videoCaption.captionClick).toHaveBeenCalled();
$(this).trigger('mousedown');
expect(state.videoCaption.captionMouseDown).toHaveBeenCalled();
$(this).trigger('mousedown');
expect(state.videoCaption.captionMouseDown).toHaveBeenCalled();
$(this).trigger('focus');
expect(state.videoCaption.captionFocus).toHaveBeenCalled();
$(this).trigger('focus');
expect(state.videoCaption.captionFocus).toHaveBeenCalled();
$(this).trigger('blur');
expect(state.videoCaption.captionBlur).toHaveBeenCalled();
$(this).trigger('blur');
expect(state.videoCaption.captionBlur).toHaveBeenCalled();
$(this).trigger('keydown');
expect(state.videoCaption.captionKeyDown).toHaveBeenCalled();
});
$(this).trigger('keydown');
expect(state.videoCaption.captionKeyDown).toHaveBeenCalled();
});
});
it('set rendered to true', function () {
runs(function () {
state = jasmine.initializePlayer();
});
it('set rendered to true', function (done) {
state = jasmine.initializePlayer();
waitsFor(function () {
jasmine.waitUntil(function () {
return state.videoCaption.rendered;
}, 'Transcripts are not rendered', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expect(state.videoCaption.rendered).toBeTruthy();
});
}).always(done);
});
});
describe('when on a touch-based device', function () {
beforeEach(function () {
window.onTouchBasedDevice.andReturn(['iPad']);
window.onTouchBasedDevice.and.returnValue(['iPad']);
state = jasmine.initializePlayer();
$.fn.scrollTo.reset();
$.fn.scrollTo.calls.reset();
});
it('show explanation message', function () {
@@ -422,30 +399,24 @@
);
});
it('show transcript on play', function () {
runs(function () {
state.el.trigger('play');
});
it('show transcript on play', function (done) {
state.el.trigger('play');
waitsFor(function () {
jasmine.waitUntil(function () {
return state.videoCaption.rendered;
}, 'Transcripts are not rendered', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
var captionsData = jasmine.stubbedCaption,
items = $('.subtitles li[data-index]');
_.each(captionsData.text, function (text, index) {
var item = items.eq(index);
expect(item).toHaveData('index', index);
expect(item).toHaveData(
'start', captionsData.start[index]
);
expect(item).toHaveAttr('tabindex', 0);
expect(item).toHaveText(text);
expect(parseIntAttribute(item, 'data-index')).toEqual(index);
expect(parseIntAttribute(item, 'data-start')).toEqual(captionsData.start[index]);
expect(item.attr('tabindex')).toEqual(0);
expect(item.text().trim()).toEqual(text);
});
});
}).always(done);
});
it('does not set rendered to true', function () {
@@ -467,62 +438,58 @@
});
});
var originalClearTimeout;
describe('mouse movement', function () {
beforeEach(function () {
jasmine.Clock.useMock();
spyOn(window, 'clearTimeout');
runs(function () {
state = jasmine.initializePlayer();
jasmine.Clock.tick(50);
});
waitsFor(function () {
beforeEach(function (done) {
jasmine.clock().install();
state = jasmine.initializePlayer();
jasmine.clock().tick(50);
jasmine.waitUntil(function () {
return state.videoCaption.rendered;
}, 'Transcripts are not rendered', WAIT_TIMEOUT);
}).then(done);
// Why we can't use spyOn(): https://github.com/jasmine/jasmine/issues/826
originalClearTimeout = window.clearTimeout;
window.clearTimeout = jasmine.createSpy().and.callFake(originalClearTimeout);
});
afterEach(function () {
window.clearTimeout = originalClearTimeout;
jasmine.clock().uninstall();
});
describe('when cursor is outside of the transcript box', function () {
it('does not set freezing timeout', function () {
runs(function () {
expect(state.videoCaption.frozen).toBeFalsy();
});
expect(state.videoCaption.frozen).toBeFalsy();
});
});
describe('when cursor is in the transcript box', function () {
beforeEach(function () {
spyOn(state.videoCaption, 'onMouseLeave');
runs(function () {
$(window).trigger(jQuery.Event('mousemove'));
jasmine.Clock.tick(state.config.captionsFreezeTime);
$('.subtitles-menu').trigger(jQuery.Event('mouseenter'));
jasmine.Clock.tick(state.config.captionsFreezeTime);
});
$(window).trigger(jQuery.Event('mousemove'));
jasmine.clock().tick(state.config.captionsFreezeTime);
$('.subtitles-menu').trigger(jQuery.Event('mouseenter'));
jasmine.clock().tick(state.config.captionsFreezeTime);
});
it('set the freezing timeout', function () {
runs(function () {
expect(state.videoCaption.frozen).not.toBeFalsy();
expect(state.videoCaption.onMouseLeave).toHaveBeenCalled();
});
expect(state.videoCaption.frozen).not.toBeFalsy();
expect(state.videoCaption.onMouseLeave).toHaveBeenCalled();
});
describe('when the cursor is moving', function () {
it('reset the freezing timeout', function () {
runs(function () {
$('.subtitles-menu').trigger(jQuery.Event('mousemove'));
expect(window.clearTimeout).toHaveBeenCalled();
});
$('.subtitles-menu').trigger(jQuery.Event('mousemove'));
expect(window.clearTimeout).toHaveBeenCalled();
});
});
describe('when the mouse is scrolling', function () {
it('reset the freezing timeout', function () {
runs(function () {
$('.subtitles-menu').trigger(jQuery.Event('mousewheel'));
expect(window.clearTimeout).toHaveBeenCalled();
});
$('.subtitles-menu').trigger(jQuery.Event('mousewheel'));
expect(window.clearTimeout).toHaveBeenCalled();
});
});
});
@@ -533,7 +500,7 @@
beforeEach(function () {
state.videoCaption.frozen = 100;
$.fn.scrollTo.reset();
$.fn.scrollTo.calls.reset();
});
describe('always', function () {
@@ -582,12 +549,12 @@
beforeEach(function () {
state = jasmine.initializePlayer();
Caption = state.videoCaption;
spyOn($, 'ajaxWithPrefix').andCallThrough();
spyOn($, 'ajaxWithPrefix').and.callThrough();
spyOn(Caption, 'renderCaption');
spyOn(Caption, 'bindHandlers');
spyOn(Caption, 'updatePlayTime');
spyOn(Caption, 'hideCaptions');
spyOn(state, 'youtubeId').andReturn('Z5KLxerq05Y');
spyOn(state, 'youtubeId').and.returnValue('Z5KLxerq05Y');
});
it('show transcript on language change', function () {
@@ -609,7 +576,7 @@
expect(Caption.hideCaptions).toHaveBeenCalledWith(false, false);
Caption.loaded = false;
Caption.hideCaptions.reset();
Caption.hideCaptions.calls.reset();
state.hide_captions = true;
Caption.fetchCaption();
@@ -683,7 +650,7 @@
msg = 'on error: transcripts are hidden if there are no transcripts';
it(msg, function () {
spyOn(Caption, 'fetchAvailableTranslations');
$.ajax.andCallFake(function (settings) {
$.ajax.and.callFake(function (settings) {
_.result(settings, 'error');
});
@@ -693,7 +660,7 @@
expect($.ajaxWithPrefix).toHaveBeenCalled();
expect(Caption.fetchAvailableTranslations).not.toHaveBeenCalled();
expect(Caption.hideCaptions.mostRecentCall.args)
expect(Caption.hideCaptions.calls.mostRecent().args)
.toEqual([true, false]);
});
@@ -701,8 +668,8 @@
'with youtubeId if there are no additional transcripts';
it(msg, function () {
spyOn(Caption, 'fetchAvailableTranslations');
spyOn(Caption, 'fetchCaption').andCallThrough();
$.ajax.andCallFake(function (settings) {
spyOn(Caption, 'fetchCaption').and.callThrough();
$.ajax.and.callFake(function (settings) {
_.result(settings, 'error');
});
@@ -712,19 +679,19 @@
Caption.fetchCaption();
expect(Caption.fetchAvailableTranslations).not.toHaveBeenCalled();
expect($.ajaxWithPrefix.mostRecentCall.args[0]['data'])
expect($.ajaxWithPrefix.calls.mostRecent().args[0].data)
.toEqual({'videoId':'Z5KLxerq05Y'});
expect(Caption.hideCaptions.mostRecentCall.args)
expect(Caption.hideCaptions.calls.mostRecent().args)
.toEqual([true, false]);
expect(Caption.fetchCaption.mostRecentCall.args[0]).toEqual(true);
expect(Caption.fetchCaption.callCount).toEqual(2);
expect(Caption.fetchCaption.calls.mostRecent().args[0]).toEqual(true);
expect(Caption.fetchCaption.calls.count()).toEqual(2);
});
msg = 'on success: when fetchCaption called with fetch_with_youtubeId to ' +
'get transcript with youtubeId for html5';
it(msg, function () {
spyOn(Caption, 'fetchAvailableTranslations');
spyOn(Caption, 'fetchCaption').andCallThrough();
spyOn(Caption, 'fetchCaption').and.callThrough();
Caption.loaded = true;
state.config.transcriptLanguages = {};
@@ -733,18 +700,18 @@
Caption.fetchCaption(true);
expect(Caption.fetchAvailableTranslations).not.toHaveBeenCalled();
expect($.ajaxWithPrefix.mostRecentCall.args[0]['data'])
expect($.ajaxWithPrefix.calls.mostRecent().args[0].data)
.toEqual({'videoId':'Z5KLxerq05Y'});
expect(Caption.hideCaptions).toHaveBeenCalledWith(false);
expect(Caption.fetchCaption.mostRecentCall.args[0]).toEqual(true);
expect(Caption.fetchCaption.callCount).toEqual(1);
expect(Caption.fetchCaption.calls.mostRecent().args[0]).toEqual(true);
expect(Caption.fetchCaption.calls.count()).toEqual(1);
});
msg = 'on error: fetch available translations if there are ' +
'additional transcripts';
it(msg, function () {
$.ajax
.andCallFake(function (settings) {
.and.callFake(function (settings) {
_.result(settings, 'error');
});
@@ -767,7 +734,7 @@
beforeEach(function () {
state = jasmine.initializePlayer();
Caption = state.videoCaption;
spyOn($, 'ajaxWithPrefix').andCallThrough();
spyOn($, 'ajaxWithPrefix').and.callThrough();
spyOn(Caption, 'hideCaptions');
spyOn(Caption, 'fetchCaption');
spyOn(Caption, 'renderLanguageMenu');
@@ -821,7 +788,7 @@
msg = 'on error: transcripts are hidden if there are no transcript';
it(msg, function () {
$.ajax.andCallFake(function (settings) {
$.ajax.and.callFake(function (settings) {
_.result(settings, 'error');
});
Caption.fetchAvailableTranslations();
@@ -834,55 +801,44 @@
describe('play', function () {
describe('when the transcript was not rendered', function () {
beforeEach(function () {
window.onTouchBasedDevice.andReturn(['iPad']);
beforeEach(function (done) {
window.onTouchBasedDevice.and.returnValue(['iPad']);
runs(function () {
state = jasmine.initializePlayer();
state.videoCaption.play();
});
state = jasmine.initializePlayer();
state.videoCaption.play();
waitsFor(function () {
jasmine.waitUntil(function () {
return state.videoCaption.rendered;
}, 'Transcripts are not rendered', WAIT_TIMEOUT);
}).then(function(){
done();
});
});
it('render the transcript', function () {
runs(function () {
var captionsData;
var captionsData;
captionsData = jasmine.stubbedCaption;
$('.subtitles li[data-index]').each(
function (index, link) {
captionsData = jasmine.stubbedCaption;
expect($(link)).toHaveData('index', index);
expect($(link)).toHaveData(
'start', captionsData.start[index]
);
expect($(link)).toHaveAttr('tabindex', 0);
expect($(link)).toHaveText(captionsData.text[index]);
});
$('.subtitles li[data-index]').each(
function (index, item) {
expect(parseIntAttribute($(item), 'data-index')).toEqual(index);
expect(parseIntAttribute($(item), 'data-start')).toEqual(captionsData.start[index]);
expect($(item).attr('tabindex')).toEqual(0);
expect($(item).text().trim()).toEqual(captionsData.text[index]);
});
});
it('add a padding element to transcript', function () {
runs(function () {
expect($('.subtitles li:first')).toBe('.spacing');
expect($('.subtitles li:last')).toBe('.spacing');
});
expect($('.subtitles li:first')).toHaveClass('spacing');
expect($('.subtitles li:last')).toHaveClass('spacing');
});
it('set rendered to true', function () {
runs(function () {
expect(state.videoCaption.rendered).toBeTruthy();
});
expect(state.videoCaption.rendered).toBeTruthy();
});
it('set playing to true', function () {
runs(function () {
expect(state.videoCaption.playing).toBeTruthy();
});
expect(state.videoCaption.playing).toBeTruthy();
});
});
});
@@ -900,178 +856,148 @@
});
describe('updatePlayTime', function () {
beforeEach(function () {
runs(function () {
state = jasmine.initializePlayer();
});
beforeEach(function (done) {
state = jasmine.initializePlayer();
waitsFor(function () {
jasmine.waitUntil(function () {
return state.videoCaption.rendered;
}, 'Transcripts are not rendered', WAIT_TIMEOUT);
}).then(done);
});
describe('when the video speed is 1.0x', function () {
it('search the caption based on time', function () {
runs(function () {
state.videoCaption.updatePlayTime(25.000);
expect(state.videoCaption.currentIndex).toEqual(5);
state.videoCaption.updatePlayTime(25.000);
expect(state.videoCaption.currentIndex).toEqual(5);
// Flash mode
spyOn(state, 'isFlashMode').andReturn(true);
state.speed = '1.0';
state.videoCaption.updatePlayTime(25.000);
expect(state.videoCaption.currentIndex).toEqual(5);
});
// Flash mode
spyOn(state, 'isFlashMode').and.returnValue(true);
state.speed = '1.0';
state.videoCaption.updatePlayTime(25.000);
expect(state.videoCaption.currentIndex).toEqual(5);
});
});
describe('when the video speed is not 1.0x', function () {
it('search the transcript based on 1.0x speed', function () {
runs(function () {
state.videoCaption.updatePlayTime(25.000);
expect(state.videoCaption.currentIndex).toEqual(5);
state.videoCaption.updatePlayTime(25.000);
expect(state.videoCaption.currentIndex).toEqual(5);
// To test speed, don't use start / end times.
state.config.startTime = 0;
state.config.endTime = null;
// To test speed, don't use start / end times.
state.config.startTime = 0;
state.config.endTime = null;
// Flash mode
state.speed = '2.0';
spyOn(state, 'isFlashMode').andReturn(true);
state.videoCaption.updatePlayTime(25.000);
expect(state.videoCaption.currentIndex).toEqual(9);
state.speed = '0.75';
state.videoCaption.updatePlayTime(25.000);
expect(state.videoCaption.currentIndex).toEqual(3);
});
// Flash mode
state.speed = '2.0';
spyOn(state, 'isFlashMode').and.returnValue(true);
state.videoCaption.updatePlayTime(25.000);
expect(state.videoCaption.currentIndex).toEqual(9);
state.speed = '0.75';
state.videoCaption.updatePlayTime(25.000);
expect(state.videoCaption.currentIndex).toEqual(3);
});
});
describe('when the index is not the same', function () {
beforeEach(function () {
runs(function () {
state.videoCaption.currentIndex = 1;
$('.subtitles li[data-index=5]').addClass('current');
state.videoCaption.updatePlayTime(25.000);
});
state.videoCaption.currentIndex = 1;
$('.subtitles li[data-index=5]').addClass('current');
state.videoCaption.updatePlayTime(25.000);
});
it('deactivate the previous transcript', function () {
runs(function () {
expect($('.subtitles li[data-index=1]'))
.not.toHaveClass('current');
});
expect($('.subtitles li[data-index=1]'))
.not.toHaveClass('current');
});
it('activate new transcript', function () {
runs(function () {
expect($('.subtitles li[data-index=5]'))
.toHaveClass('current');
});
expect($('.subtitles li[data-index=5]'))
.toHaveClass('current');
});
it('save new index', function () {
runs(function () {
expect(state.videoCaption.currentIndex).toEqual(5);
});
expect(state.videoCaption.currentIndex).toEqual(5);
});
it('scroll transcript to new position', function () {
runs(function () {
expect($.fn.scrollTo).toHaveBeenCalled();
});
expect($.fn.scrollTo).toHaveBeenCalled();
});
});
describe('when the index is the same', function () {
it('does not change current subtitle', function () {
runs(function () {
state.videoCaption.currentIndex = 1;
$('.subtitles li[data-index=3]').addClass('current');
state.videoCaption.updatePlayTime(15.000);
expect($('.subtitles li[data-index=3]'))
.toHaveClass('current');
});
state.videoCaption.currentIndex = 1;
$('.subtitles li[data-index=3]').addClass('current');
state.videoCaption.updatePlayTime(15.000);
expect($('.subtitles li[data-index=3]'))
.toHaveClass('current');
});
});
});
describe('resize', function () {
beforeEach(function () {
runs(function () {
state = jasmine.initializePlayer();
});
beforeEach(function (done) {
state = jasmine.initializePlayer();
waitsFor(function () {
jasmine.waitUntil(function () {
return state.videoCaption.rendered;
}, 'Transcripts are not rendered', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
videoControl = state.videoControl;
$('.subtitles li[data-index=1]').addClass('current');
state.videoCaption.onResize();
});
}).always(done);
});
describe('set the height of transcript container', function () {
it('when transcript button is enabled', function () {
runs(function () {
var realHeight = parseInt(
$('.subtitles').css('maxHeight'), 10
),
shouldBeHeight = $('.video-wrapper').height();
var realHeight = parseInt(
$('.subtitles').css('maxHeight'), 10
),
shouldBeHeight = $('.video-wrapper').height();
// Because of some problems with rounding on different
// environments: Linux * Mac * FF * Chrome
expect(realHeight).toBeCloseTo(shouldBeHeight, 2);
});
// Because of some problems with rounding on different
// environments: Linux * Mac * FF * Chrome
expect(realHeight).toBeCloseTo(shouldBeHeight, 2);
});
it('when transcript button is disabled ', function () {
runs(function () {
var realHeight, videoWrapperHeight, progressSliderHeight,
controlHeight, shouldBeHeight;
var realHeight, videoWrapperHeight, progressSliderHeight,
controlHeight, shouldBeHeight;
state.captionsHidden = true;
state.videoCaption.setSubtitlesHeight();
state.captionsHidden = true;
state.videoCaption.setSubtitlesHeight();
realHeight = parseInt(
$('.subtitles').css('maxHeight'), 10
);
videoWrapperHeight = $('.video-wrapper').height();
progressSliderHeight = state.el.find('.slider').height();
controlHeight = state.el.find('.video-controls').height();
shouldBeHeight = videoWrapperHeight -
0.5 * progressSliderHeight -
controlHeight;
realHeight = parseInt(
$('.subtitles').css('maxHeight'), 10
);
videoWrapperHeight = $('.video-wrapper').height();
progressSliderHeight = state.el.find('.slider').height();
controlHeight = state.el.find('.video-controls').height();
shouldBeHeight = videoWrapperHeight -
0.5 * progressSliderHeight -
controlHeight;
expect(realHeight).toBe(shouldBeHeight);
});
expect(realHeight).toBe(shouldBeHeight);
});
});
it('set the height of transcript spacing', function () {
runs(function () {
var firstSpacing, lastSpacing;
var firstSpacing, lastSpacing;
firstSpacing = Math.abs(parseInt(
$('.subtitles .spacing:first').css('height'), 10
));
lastSpacing = Math.abs(parseInt(
$('.subtitles .spacing:last').css('height'), 10
));
firstSpacing = Math.abs(parseInt(
$('.subtitles .spacing:first').css('height'), 10
));
lastSpacing = Math.abs(parseInt(
$('.subtitles .spacing:last').css('height'), 10
));
expect(firstSpacing - state.videoCaption.topSpacingHeight())
.toBeLessThan(1);
expect(lastSpacing - state.videoCaption.bottomSpacingHeight())
.toBeLessThan(1);
});
expect(firstSpacing - state.videoCaption.topSpacingHeight())
.toBeLessThan(1);
expect(lastSpacing - state.videoCaption.bottomSpacingHeight())
.toBeLessThan(1);
});
it('scroll transcript to new position', function () {
runs(function () {
expect($.fn.scrollTo).toHaveBeenCalled();
});
expect($.fn.scrollTo).toHaveBeenCalled();
});
});
@@ -1193,7 +1119,11 @@
beforeEach(function () {
state.el.addClass('closed');
state.videoCaption.toggle(jQuery.Event('click'));
jasmine.Clock.useMock();
jasmine.clock().install();
});
afterEach(function () {
jasmine.clock().uninstall();
});
it('show the transcript', function () {
@@ -1204,7 +1134,7 @@
xit('scroll the transcript', function () {
// After transcripts are shown, and the video plays for a
// bit.
jasmine.Clock.tick(1000);
jasmine.clock().tick(1000);
// The transcripts should have advanced by at least one
// position. When they advance, the list scrolls. The
@@ -1218,60 +1148,46 @@
});
describe('transcript accessibility', function () {
beforeEach(function () {
runs(function () {
state = jasmine.initializePlayer();
});
beforeEach(function (done) {
state = jasmine.initializePlayer();
waitsFor(function () {
jasmine.waitUntil(function () {
return state.videoCaption.rendered;
}, 'Transcripts are not rendered', WAIT_TIMEOUT);
}).then(done);
});
describe('when getting focus through TAB key', function () {
beforeEach(function () {
runs(function () {
state.videoCaption.isMouseFocus = false;
$('.subtitles li[data-index=0]').trigger(
jQuery.Event('focus')
);
});
state.videoCaption.isMouseFocus = false;
$('.subtitles li[data-index=0]').trigger(
jQuery.Event('focus')
);
});
it('shows an outline around the transcript', function () {
runs(function () {
expect($('.subtitles li[data-index=0]'))
.toHaveClass('focused');
});
expect($('.subtitles li[data-index=0]'))
.toHaveClass('focused');
});
it('has automatic scrolling disabled', function () {
runs(function () {
expect(state.videoCaption.autoScrolling).toBe(false);
});
expect(state.videoCaption.autoScrolling).toBe(false);
});
});
describe('when loosing focus through TAB key', function () {
beforeEach(function () {
runs(function () {
$('.subtitles li[data-index=0]').trigger(
jQuery.Event('blur')
);
});
$('.subtitles li[data-index=0]').trigger(
jQuery.Event('blur')
);
});
it('does not show an outline around the transcript', function () {
runs(function () {
expect($('.subtitles li[data-index=0]'))
.not.toHaveClass('focused');
});
expect($('.subtitles li[data-index=0]'))
.not.toHaveClass('focused');
});
it('has automatic scrolling enabled', function () {
runs(function () {
expect(state.videoCaption.autoScrolling).toBe(true);
});
expect(state.videoCaption.autoScrolling).toBe(true);
});
});
@@ -1281,26 +1197,20 @@
function () {
beforeEach(function () {
runs(function () {
state.videoCaption.isMouseFocus = false;
$('.subtitles li[data-index=0]')
.trigger(jQuery.Event('focus'));
$('.subtitles li[data-index=0]')
.trigger(jQuery.Event('mousedown'));
});
state.videoCaption.isMouseFocus = false;
$('.subtitles li[data-index=0]')
.trigger(jQuery.Event('focus'));
$('.subtitles li[data-index=0]')
.trigger(jQuery.Event('mousedown'));
});
it('does not show an outline around it', function () {
runs(function () {
expect($('.subtitles li[data-index=0]'))
.not.toHaveClass('focused');
});
expect($('.subtitles li[data-index=0]'))
.not.toHaveClass('focused');
});
it('has automatic scrolling enabled', function () {
runs(function () {
expect(state.videoCaption.autoScrolling).toBe(true);
});
expect(state.videoCaption.autoScrolling).toBe(true);
});
});
@@ -1312,37 +1222,29 @@
var subDataLiIdx__0, subDataLiIdx__1;
beforeEach(function () {
runs(function () {
subDataLiIdx__0 = $('.subtitles li[data-index=0]');
subDataLiIdx__1 = $('.subtitles li[data-index=1]');
subDataLiIdx__0 = $('.subtitles li[data-index=0]');
subDataLiIdx__1 = $('.subtitles li[data-index=1]');
state.videoCaption.isMouseFocus = false;
state.videoCaption.isMouseFocus = false;
subDataLiIdx__0.trigger(jQuery.Event('focus'));
subDataLiIdx__0.trigger(jQuery.Event('blur'));
subDataLiIdx__0.trigger(jQuery.Event('focus'));
subDataLiIdx__0.trigger(jQuery.Event('blur'));
state.videoCaption.isMouseFocus = true;
state.videoCaption.isMouseFocus = true;
subDataLiIdx__1.trigger(jQuery.Event('mousedown'));
});
subDataLiIdx__1.trigger(jQuery.Event('mousedown'));
});
it('does not show an outline around the first', function () {
runs(function () {
expect(subDataLiIdx__0).not.toHaveClass('focused');
});
expect(subDataLiIdx__0).not.toHaveClass('focused');
});
it('does not show an outline around the second', function () {
runs(function () {
expect(subDataLiIdx__1).not.toHaveClass('focused');
});
expect(subDataLiIdx__1).not.toHaveClass('focused');
});
it('has automatic scrolling enabled', function () {
runs(function () {
expect(state.videoCaption.autoScrolling).toBe(true);
});
expect(state.videoCaption.autoScrolling).toBe(true);
});
});
});

View File

@@ -6,7 +6,6 @@
openMenu = function () {
var container = $('.video');
jasmine.Clock.useMock();
container.find('video').trigger('contextmenu');
menu = container.children('.contextmenu');
menuItems = menu.children('.menu-item').not('.submenu-item');
@@ -23,19 +22,19 @@
openSubmenuMouse = function (menuSubmenuItem) {
menuSubmenuItem.mouseover();
jasmine.Clock.tick(200);
jasmine.clock().tick(200);
expect(menuSubmenuItem).toHaveClass('is-opened');
};
openSubmenuKeyboard = function (menuSubmenuItem, keyCode) {
menuSubmenuItem.focus().trigger(keyPressEvent(keyCode || $.ui.keyCode.RIGHT));
expect(menuSubmenuItem).toHaveClass('is-opened');
expect(menuSubmenuItem.children().first()).toBeFocused();
expect(menuSubmenuItem.children().last().children().first()).toBeFocused();
};
closeSubmenuMouse = function (menuSubmenuItem) {
menuSubmenuItem.mouseleave();
jasmine.Clock.tick(200);
jasmine.clock().tick(200);
expect(menuSubmenuItem).not.toHaveClass('is-opened');
};
@@ -46,20 +45,20 @@
};
beforeEach(function () {
jasmine.clock().install();
// $.cookie is mocked, make sure we have a state with an unmuted volume.
$.cookie.andReturn('100');
this.addMatchers({
toBeFocused: function () {
$.cookie.and.returnValue('100');
jasmine.addMatchers({
toHaveCorrectLabels: function () {
return {
compare: function (actual) {
return { pass: $(actual)[0] === $(actual)[0].ownerDocument.activeElement };
compare: function (actual, labelsList) {
return {
pass: _.difference(labelsList, _.map(actual, function (item) {
return $(item).text();
})).length === 0
};
}
};
},
toHaveCorrectLabels: function (labelsList) {
return _.difference(labelsList, _.map(this.actual, function (item) {
return $(item).text();
})).length === 0;
}
});
});
@@ -69,6 +68,7 @@
_.result(state.storage, 'clear');
_.result($('video').data('contextmenu'), 'destroy');
_.result(state.videoPlayer, 'destroy');
jasmine.clock().uninstall();
});
describe('constructor', function () {
@@ -89,7 +89,7 @@
*/
// Only one context menu per video container
expect(menu).toExist();
expect(menu).toBeInDOM();
expect(menu).toHaveClass('is-opened');
expect(menuItems).toHaveCorrectLabels(['Play', 'Mute', 'Fill browser']);
expect(menuSubmenuItem.children('span')).toHaveText('Speed');
@@ -141,8 +141,8 @@
menuEvents = ['keydown', 'contextmenu', 'mouseleave', 'mouseover'];
menu.data('menu').destroy();
expect(menu).not.toExist();
expect(overlay).not.toExist();
expect(menu).not.toBeInDOM();
expect(overlay).not.toBeInDOM();
_.each(menuitemEvents, function (eventName) {
expect(menuItems.first()).not.toHandle(eventName);
})
@@ -177,7 +177,7 @@
it('context menu opens', function () {
expect(menu).toHaveClass('is-opened');
expect(overlay).toExist();
expect(overlay).toBeInDOM();
});
it('mouseover and mouseleave behave as expected', function () {
@@ -193,25 +193,25 @@
// Left-click outside of open menu, for example on Play button
playButton.click();
expect(menu).not.toHaveClass('is-opened');
expect(overlay).not.toExist();
expect(overlay).not.toBeInDOM();
});
it('mouse right-clicking outside of video will close it', function () {
// Right-click outside of open menu for example on Play button
playButton.trigger('contextmenu');
expect(menu).not.toHaveClass('is-opened');
expect(overlay).not.toExist();
expect(overlay).not.toBeInDOM();
});
it('mouse right-clicking inside video but outside of context menu will not close it', function () {
spyOn(menu.data('menu'), 'pointInContainerBox').andReturn(true);
spyOn(menu.data('menu'), 'pointInContainerBox').and.returnValue(true);
overlay.trigger('contextmenu');
expect(menu).toHaveClass('is-opened');
expect(overlay).toExist();
expect(overlay).toBeInDOM();
});
it('mouse right-clicking inside video but outside of context menu will close submenus', function () {
spyOn(menu.data('menu'), 'pointInContainerBox').andReturn(true);
spyOn(menu.data('menu'), 'pointInContainerBox').and.returnValue(true);
openSubmenuMouse(menuSubmenuItem);
expect(menuSubmenuItem).toHaveClass('is-opened');
overlay.trigger('contextmenu');
@@ -221,12 +221,12 @@
it('mouse left/right-clicking behaves as expected on play/pause menu item', function () {
var menuItem = menuItems.first();
spyOn(state.videoPlayer, 'isPlaying');
spyOn(state.videoPlayer, 'play').andCallFake(function () {
state.videoPlayer.isPlaying.andReturn(true);
spyOn(state.videoPlayer, 'play').and.callFake(function () {
state.videoPlayer.isPlaying.and.returnValue(true);
state.el.trigger('play');
});
spyOn(state.videoPlayer, 'pause').andCallFake(function () {
state.videoPlayer.isPlaying.andReturn(false);
spyOn(state.videoPlayer, 'pause').and.callFake(function () {
state.videoPlayer.isPlaying.and.returnValue(false);
state.el.trigger('pause');
});
// Left-click on play
@@ -238,7 +238,7 @@
menuItem.click();
expect(state.videoPlayer.pause).toHaveBeenCalled();
expect(menuItem).toHaveText('Play');
state.videoPlayer.play.reset();
state.videoPlayer.play.calls.reset();
// Right-click on play
menuItem.trigger('contextmenu');
expect(state.videoPlayer.play).toHaveBeenCalled();
@@ -355,14 +355,14 @@
it('close the menu on ESCAPE keydown', function () {
menu.trigger(keyPressEvent($.ui.keyCode.ESCAPE));
expect(menu).not.toHaveClass('is-opened');
expect(overlay).not.toExist();
expect(overlay).not.toBeInDOM();
});
it('close the submenu on ESCAPE keydown', function () {
openSubmenuKeyboard(menuSubmenuItem);
menuSubmenuItem.trigger(keyPressEvent($.ui.keyCode.ESCAPE));
expect(menuSubmenuItem).not.toHaveClass('is-opened');
expect(overlay).not.toExist();
expect(overlay).not.toBeInDOM();
});
it('close the submenu on LEFT keydown on submenu items', function () {
@@ -395,9 +395,9 @@
menuItems.eq(0).trigger(keyPressEvent($.ui.keyCode.UP));
expect(menuSubmenuItem).toBeFocused(); // Speed
menuSubmenuItem.trigger(keyPressEvent($.ui.keyCode.UP));
// Check if hidden item can be skipped correctly.
menuItems.eq(2).hide(); // hide Fullscreen item
menuSubmenuItem.trigger(keyPressEvent($.ui.keyCode.UP));
expect(menuItems.eq(1)).toBeFocused(); // Mute
menuItems.eq(1).trigger(keyPressEvent($.ui.keyCode.UP));
expect(menuItems.eq(0)).toBeFocused(); // Play

View File

@@ -7,7 +7,7 @@
beforeEach(function () {
oldOTBD = window.onTouchBasedDevice;
window.onTouchBasedDevice = jasmine
.createSpy('onTouchBasedDevice').andReturn(null);
.createSpy('onTouchBasedDevice').and.returnValue(null);
});
afterEach(function () {
@@ -24,7 +24,7 @@
});
it('render the video controls', function () {
expect($('.video-controls')).toContain(
expect($('.video-controls')).toContainElement(
[
'.slider',
'ul.vcr',
@@ -41,61 +41,52 @@
describe('constructor with start-time', function () {
it(
'saved position is 0, timer slider and VCR set to start-time',
function ()
function (done)
{
var duration, sliderEl, expectedValue;
runs(function () {
window.VideoState = {};
state = jasmine.initializePlayer({
start: 10,
savedVideoPosition: 0
});
sliderEl = state.videoProgressSlider.slider;
spyOn(state.videoPlayer, 'duration').andReturn(60);
window.VideoState = {};
state = jasmine.initializePlayer({
start: 10,
savedVideoPosition: 0
});
sliderEl = state.videoProgressSlider.slider;
spyOn(state.videoPlayer, 'duration').and.returnValue(60);
waitsFor(function () {
jasmine.waitUntil(function () {
duration = state.videoPlayer.duration();
return isFinite(duration) && duration > 0 &&
isFinite(state.videoPlayer.startTime);
}, 'duration is set', WAIT_TIMEOUT);
runs(function () {
return isFinite(duration) && duration > 0 && isFinite(state.videoPlayer.startTime);
}).then(function () {
expectedValue = $('.video-controls').find('.vidtime');
expect(expectedValue).toHaveText('0:10 / 1:00');
expectedValue = sliderEl.slider('option', 'value');
expect(expectedValue).toBe(10);
});
}).always(done);
});
it(
'saved position is after start-time, ' +
'timer slider and VCR set to saved position',
function ()
function (done)
{
var duration, sliderEl, expectedValue;
runs(function () {
window.VideoState = {};
state = jasmine.initializePlayer({
start: 10,
savedVideoPosition: 15
});
sliderEl = state.videoProgressSlider.slider;
spyOn(state.videoPlayer, 'duration').andReturn(60);
window.VideoState = {};
state = jasmine.initializePlayer({
start: 10,
savedVideoPosition: 15
});
sliderEl = state.videoProgressSlider.slider;
spyOn(state.videoPlayer, 'duration').and.returnValue(60);
waitsFor(function () {
jasmine.waitUntil(function () {
duration = state.videoPlayer.duration();
return isFinite(duration) && duration > 0 &&
isFinite(state.videoPlayer.startTime);
}, 'duration is set', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expectedValue = $('.video-controls').find('.vidtime');
expect(expectedValue).toHaveText('0:15 / 1:00');
@@ -103,34 +94,30 @@
expect(expectedValue).toBe(15);
state.storage.clear();
});
}).always(done);
});
it(
'saved position is negative, ' +
'timer slider and VCR set to start-time',
function ()
function (done)
{
var duration, sliderEl, expectedValue;
runs(function () {
window.VideoState = {};
state = jasmine.initializePlayer({
start: 10,
savedVideoPosition: -15
});
sliderEl = state.videoProgressSlider.slider;
spyOn(state.videoPlayer, 'duration').andReturn(60);
window.VideoState = {};
state = jasmine.initializePlayer({
start: 10,
savedVideoPosition: -15
});
sliderEl = state.videoProgressSlider.slider;
spyOn(state.videoPlayer, 'duration').and.returnValue(60);
waitsFor(function () {
jasmine.waitUntil(function () {
duration = state.videoPlayer.duration();
return isFinite(duration) && duration > 0 &&
isFinite(state.videoPlayer.startTime);
}, 'duration is set', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expectedValue = $('.video-controls').find('.vidtime');
expect(expectedValue).toHaveText('0:10 / 1:00');
@@ -138,34 +125,30 @@
expect(expectedValue).toBe(10);
state.storage.clear();
});
}).always(done);
});
it(
'saved position is not a number, ' +
'timer slider and VCR set to start-time',
function ()
function (done)
{
var duration, sliderEl, expectedValue;
runs(function () {
window.VideoState = {};
state = jasmine.initializePlayer({
start: 10,
savedVideoPosition: 'a'
});
sliderEl = state.videoProgressSlider.slider;
spyOn(state.videoPlayer, 'duration').andReturn(60);
window.VideoState = {};
state = jasmine.initializePlayer({
start: 10,
savedVideoPosition: 'a'
});
sliderEl = state.videoProgressSlider.slider;
spyOn(state.videoPlayer, 'duration').and.returnValue(60);
waitsFor(function () {
jasmine.waitUntil(function () {
duration = state.videoPlayer.duration();
return isFinite(duration) && duration > 0 &&
isFinite(state.videoPlayer.startTime);
}, 'duration is set', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expectedValue = $('.video-controls').find('.vidtime');
expect(expectedValue).toHaveText('0:10 / 1:00');
@@ -173,34 +156,30 @@
expect(expectedValue).toBe(10);
state.storage.clear();
});
}).always(done);
});
it(
'saved position is greater than end-time, ' +
'timer slider and VCR set to start-time',
function ()
function (done)
{
var duration, sliderEl, expectedValue;
runs(function () {
window.VideoState = {};
state = jasmine.initializePlayer({
start: 10,
savedVideoPosition: 10000
});
sliderEl = state.videoProgressSlider.slider;
spyOn(state.videoPlayer, 'duration').andReturn(60);
window.VideoState = {};
state = jasmine.initializePlayer({
start: 10,
savedVideoPosition: 10000
});
sliderEl = state.videoProgressSlider.slider;
spyOn(state.videoPlayer, 'duration').and.returnValue(60);
waitsFor(function () {
jasmine.waitUntil(function () {
duration = state.videoPlayer.duration();
return isFinite(duration) && duration > 0 &&
isFinite(state.videoPlayer.startTime);
}, 'duration is set', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expectedValue = $('.video-controls').find('.vidtime');
expect(expectedValue).toHaveText('0:10 / 1:00');
@@ -208,7 +187,7 @@
expect(expectedValue).toBe(10);
state.storage.clear();
});
}).always(done);
});
});
@@ -216,28 +195,24 @@
it(
'saved position is 0, timer slider and VCR set to 0:00 ' +
'and ending at specified end-time',
function ()
function (done)
{
var duration, sliderEl, expectedValue;
runs(function () {
window.VideoState = {};
state = jasmine.initializePlayer({
end: 20,
savedVideoPosition: 0
});
sliderEl = state.videoProgressSlider.slider;
spyOn(state.videoPlayer, 'duration').andReturn(60);
window.VideoState = {};
state = jasmine.initializePlayer({
end: 20,
savedVideoPosition: 0
});
sliderEl = state.videoProgressSlider.slider;
spyOn(state.videoPlayer, 'duration').and.returnValue(60);
waitsFor(function () {
jasmine.waitUntil(function () {
duration = state.videoPlayer.duration();
return isFinite(duration) && duration > 0 &&
isFinite(state.videoPlayer.startTime);
}, 'duration is set', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expectedValue = $('.video-controls').find('.vidtime');
expect(expectedValue).toHaveText('0:00 / 0:20');
@@ -245,34 +220,30 @@
expect(expectedValue).toBe(0);
state.storage.clear();
});
}).always(done);
});
it(
'saved position is after start-time, ' +
'timer slider and VCR set to saved position',
function ()
function (done)
{
var duration, sliderEl, expectedValue;
runs(function () {
window.VideoState = {};
state = jasmine.initializePlayer({
end: 20,
savedVideoPosition: 15
});
sliderEl = state.videoProgressSlider.slider;
spyOn(state.videoPlayer, 'duration').andReturn(60);
window.VideoState = {};
state = jasmine.initializePlayer({
end: 20,
savedVideoPosition: 15
});
sliderEl = state.videoProgressSlider.slider;
spyOn(state.videoPlayer, 'duration').and.returnValue(60);
waitsFor(function () {
jasmine.waitUntil(function () {
duration = state.videoPlayer.duration();
return isFinite(duration) && duration > 0 &&
isFinite(state.videoPlayer.startTime);
}, 'duration is set', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expectedValue = $('.video-controls').find('.vidtime');
expect(expectedValue).toHaveText('0:15 / 0:20');
@@ -280,34 +251,30 @@
expect(expectedValue).toBe(15);
state.storage.clear();
});
}).always(done);
});
// TODO: Fix!
it(
'saved position is negative, timer slider and VCR set to 0:00',
function ()
function (done)
{
var duration, sliderEl, expectedValue;
runs(function () {
window.VideoState = {};
state = jasmine.initializePlayer({
end: 20,
savedVideoPosition: -15
});
sliderEl = state.videoProgressSlider.slider;
spyOn(state.videoPlayer, 'duration').andReturn(60);
window.VideoState = {};
state = jasmine.initializePlayer({
end: 20,
savedVideoPosition: -15
});
sliderEl = state.videoProgressSlider.slider;
spyOn(state.videoPlayer, 'duration').and.returnValue(60);
waitsFor(function () {
jasmine.waitUntil(function () {
duration = state.videoPlayer.duration();
return isFinite(duration) && duration > 0 &&
isFinite(state.videoPlayer.startTime);
}, 'duration is set', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expectedValue = $('.video-controls').find('.vidtime');
expect(expectedValue).toHaveText('0:00 / 0:20');
@@ -315,34 +282,30 @@
expect(expectedValue).toBe(0);
state.storage.clear();
});
}).always(done);
});
it(
'saved position is not a number, ' +
'timer slider and VCR set to 0:00',
function ()
function (done)
{
var duration, sliderEl, expectedValue;
runs(function () {
window.VideoState = {};
state = jasmine.initializePlayer({
end: 20,
savedVideoPosition: 'a'
});
sliderEl = state.videoProgressSlider.slider;
spyOn(state.videoPlayer, 'duration').andReturn(60);
window.VideoState = {};
state = jasmine.initializePlayer({
end: 20,
savedVideoPosition: 'a'
});
sliderEl = state.videoProgressSlider.slider;
spyOn(state.videoPlayer, 'duration').and.returnValue(60);
waitsFor(function () {
jasmine.waitUntil(function () {
duration = state.videoPlayer.duration();
return isFinite(duration) && duration > 0 &&
isFinite(state.videoPlayer.startTime);
}, 'duration is set', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expectedValue = $('.video-controls').find('.vidtime');
expect(expectedValue).toHaveText('0:00 / 0:20');
@@ -350,35 +313,31 @@
expect(expectedValue).toBe(0);
state.storage.clear();
});
}).always(done);
});
// TODO: Fix!
it(
'saved position is greater than end-time, ' +
'timer slider and VCR set to 0:00',
function ()
function (done)
{
var duration, sliderEl, expectedValue;
runs(function () {
window.VideoState = {};
state = jasmine.initializePlayer({
end: 20,
savedVideoPosition: 10000
});
sliderEl = state.videoProgressSlider.slider;
spyOn(state.videoPlayer, 'duration').andReturn(60);
window.VideoState = {};
state = jasmine.initializePlayer({
end: 20,
savedVideoPosition: 10000
});
sliderEl = state.videoProgressSlider.slider;
spyOn(state.videoPlayer, 'duration').and.returnValue(60);
waitsFor(function () {
jasmine.waitUntil(function () {
duration = state.videoPlayer.duration();
return isFinite(duration) && duration > 0 &&
isFinite(state.videoPlayer.startTime);
}, 'duration is set', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expectedValue = $('.video-controls').find('.vidtime');
expect(expectedValue).toHaveText('0:00 / 0:20');
@@ -386,36 +345,32 @@
expect(expectedValue).toBe(0);
state.storage.clear();
});
}).always(done);
});
});
describe('constructor with start-time and end-time', function () {
it(
'saved position is 0, timer slider and VCR set to appropriate start and end times',
function ()
function (done)
{
var duration, sliderEl, expectedValue;
runs(function () {
window.VideoState = {};
state = jasmine.initializePlayer({
start: 10,
end: 20,
savedVideoPosition: 0
});
sliderEl = state.videoProgressSlider.slider;
spyOn(state.videoPlayer, 'duration').andReturn(60);
window.VideoState = {};
state = jasmine.initializePlayer({
start: 10,
end: 20,
savedVideoPosition: 0
});
sliderEl = state.videoProgressSlider.slider;
spyOn(state.videoPlayer, 'duration').and.returnValue(60);
waitsFor(function () {
jasmine.waitUntil(function () {
duration = state.videoPlayer.duration();
return isFinite(duration) && duration > 0 &&
isFinite(state.videoPlayer.startTime);
}, 'duration is set', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expectedValue = $('.video-controls').find('.vidtime');
expect(expectedValue).toHaveText('0:10 / 0:20');
@@ -423,35 +378,31 @@
expect(expectedValue).toBe(10);
state.storage.clear();
});
}).always(done);
});
it(
'saved position is after start-time, ' +
'timer slider and VCR set to saved position',
function ()
function (done)
{
var duration, sliderEl, expectedValue;
runs(function () {
window.VideoState = {};
state = jasmine.initializePlayer({
start: 10,
end: 20,
savedVideoPosition: 15
});
sliderEl = state.videoProgressSlider.slider;
spyOn(state.videoPlayer, 'duration').andReturn(60);
window.VideoState = {};
state = jasmine.initializePlayer({
start: 10,
end: 20,
savedVideoPosition: 15
});
sliderEl = state.videoProgressSlider.slider;
spyOn(state.videoPlayer, 'duration').and.returnValue(60);
waitsFor(function () {
jasmine.waitUntil(function () {
duration = state.videoPlayer.duration();
return isFinite(duration) && duration > 0 &&
isFinite(state.videoPlayer.startTime);
}, 'duration is set', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expectedValue = $('.video-controls').find('.vidtime');
expect(expectedValue).toHaveText('0:15 / 0:20');
@@ -459,35 +410,31 @@
expect(expectedValue).toBe(15);
state.storage.clear();
});
}).always(done);
});
it(
'saved position is negative, ' +
'timer slider and VCR set to start-time',
function ()
function (done)
{
var duration, sliderEl, expectedValue;
runs(function () {
window.VideoState = {};
state = jasmine.initializePlayer({
start: 10,
end: 20,
savedVideoPosition: -15
});
sliderEl = state.videoProgressSlider.slider;
spyOn(state.videoPlayer, 'duration').andReturn(60);
window.VideoState = {};
state = jasmine.initializePlayer({
start: 10,
end: 20,
savedVideoPosition: -15
});
sliderEl = state.videoProgressSlider.slider;
spyOn(state.videoPlayer, 'duration').and.returnValue(60);
waitsFor(function () {
jasmine.waitUntil(function () {
duration = state.videoPlayer.duration();
return isFinite(duration) && duration > 0 &&
isFinite(state.videoPlayer.startTime);
}, 'duration is set', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expectedValue = $('.video-controls').find('.vidtime');
expect(expectedValue).toHaveText('0:10 / 0:20');
@@ -495,35 +442,31 @@
expect(expectedValue).toBe(10);
state.storage.clear();
});
}).always(done);
});
it(
'saved position is not a number, ' +
'timer slider and VCR set to start-time',
function ()
function (done)
{
var duration, sliderEl, expectedValue;
runs(function () {
window.VideoState = {};
state = jasmine.initializePlayer({
start: 10,
end: 20,
savedVideoPosition: 'a'
});
sliderEl = state.videoProgressSlider.slider;
spyOn(state.videoPlayer, 'duration').andReturn(60);
window.VideoState = {};
state = jasmine.initializePlayer({
start: 10,
end: 20,
savedVideoPosition: 'a'
});
sliderEl = state.videoProgressSlider.slider;
spyOn(state.videoPlayer, 'duration').and.returnValue(60);
waitsFor(function () {
jasmine.waitUntil(function () {
duration = state.videoPlayer.duration();
return isFinite(duration) && duration > 0 &&
isFinite(state.videoPlayer.startTime);
}, 'duration is set', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expectedValue = $('.video-controls').find('.vidtime');
expect(expectedValue).toHaveText('0:10 / 0:20');
@@ -531,35 +474,31 @@
expect(expectedValue).toBe(10);
state.storage.clear();
});
}).always(done);
});
it(
'saved position is greater than end-time, ' +
'timer slider and VCR set to start-time',
function ()
function (done)
{
var duration, sliderEl, expectedValue;
runs(function () {
window.VideoState = {};
state = jasmine.initializePlayer({
start: 10,
end: 20,
savedVideoPosition: 10000
});
sliderEl = state.videoProgressSlider.slider;
spyOn(state.videoPlayer, 'duration').andReturn(60);
window.VideoState = {};
state = jasmine.initializePlayer({
start: 10,
end: 20,
savedVideoPosition: 10000
});
sliderEl = state.videoProgressSlider.slider;
spyOn(state.videoPlayer, 'duration').and.returnValue(60);
waitsFor(function () {
jasmine.waitUntil(function () {
duration = state.videoPlayer.duration();
return isFinite(duration) && duration > 0 &&
isFinite(state.videoPlayer.startTime);
}, 'duration is set', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expectedValue = $('.video-controls').find('.vidtime');
expect(expectedValue).toHaveText('0:10 / 0:20');
@@ -567,7 +506,7 @@
expect(expectedValue).toBe(10);
state.storage.clear();
});
}).always(done);
});
});
@@ -587,16 +526,15 @@
expect(state.videoControl).toBeUndefined();
});
it('can focus the first control', function () {
it('can focus the first control', function (done) {
var btnPlay;
state = jasmine.initializePlayer({focusFirstControl: true});
btnPlay = state.el.find('.video-controls .play');
waitsFor(function () {
jasmine.waitUntil(function () {
return state.el.hasClass('is-initialized');
}, 'Player is not initialized', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expect(btnPlay).toBeFocused();
});
}).always(done);
});
});
}).call(this, window.WAIT_TIMEOUT);

View File

@@ -1,20 +1,20 @@
(function (undefined) {
'use strict';
describe('VideoPlayer Events Bumper plugin', function () {
var Logger = window.Logger;
var state, oldOTBD;
beforeEach(function () {
oldOTBD = window.onTouchBasedDevice;
window.onTouchBasedDevice = jasmine
.createSpy('onTouchBasedDevice')
.andReturn(null);
.and.returnValue(null);
jasmine.stubRequests();
state = jasmine.initializePlayer('video_with_bumper.html');
spyOn(Logger, 'log');
$('.poster .btn-play').click();
spyOn(state.bumperState.videoEventsBumperPlugin, 'getCurrentTime').andReturn(10);
spyOn(state.bumperState.videoEventsBumperPlugin, 'getDuration').andReturn(20);
spyOn(state.bumperState.videoEventsBumperPlugin, 'getCurrentTime').and.returnValue(10);
spyOn(state.bumperState.videoEventsBumperPlugin, 'getDuration').and.returnValue(20);
});
afterEach(function () {
@@ -33,7 +33,7 @@
state.el.trigger('ready');
expect(Logger.log).toHaveBeenCalledWith('edx.video.bumper.loaded', {
host_component_id: 'id',
bumper_id: 'xmodule/include/fixtures/test.mp4',
bumper_id: '/base/fixtures/test.mp4',
code: 'html5',
duration: 20
});
@@ -43,7 +43,7 @@
state.el.trigger('play');
expect(Logger.log).toHaveBeenCalledWith('edx.video.bumper.played', {
host_component_id: 'id',
bumper_id: 'xmodule/include/fixtures/test.mp4',
bumper_id: '/base/fixtures/test.mp4',
code: 'html5',
currentTime: 10,
duration: 20
@@ -54,17 +54,17 @@
state.el.trigger('ended');
expect(Logger.log).toHaveBeenCalledWith('edx.video.bumper.stopped', {
host_component_id: 'id',
bumper_id: 'xmodule/include/fixtures/test.mp4',
bumper_id: '/base/fixtures/test.mp4',
code: 'html5',
currentTime: 10,
duration: 20
});
Logger.log.reset();
Logger.log.calls.reset();
state.el.trigger('stop');
expect(Logger.log).toHaveBeenCalledWith('edx.video.bumper.stopped', {
host_component_id: 'id',
bumper_id: 'xmodule/include/fixtures/test.mp4',
bumper_id: '/base/fixtures/test.mp4',
code: 'html5',
currentTime: 10,
duration: 20
@@ -75,7 +75,7 @@
state.el.trigger('skip', [false]);
expect(Logger.log).toHaveBeenCalledWith('edx.video.bumper.skipped', {
host_component_id: 'id',
bumper_id: 'xmodule/include/fixtures/test.mp4',
bumper_id: '/base/fixtures/test.mp4',
code: 'html5',
currentTime: 10,
duration: 20
@@ -86,7 +86,7 @@
state.el.trigger('skip', [true]);
expect(Logger.log).toHaveBeenCalledWith('edx.video.bumper.dismissed', {
host_component_id: 'id',
bumper_id: 'xmodule/include/fixtures/test.mp4',
bumper_id: '/base/fixtures/test.mp4',
code: 'html5',
currentTime: 10,
duration: 20
@@ -97,7 +97,7 @@
state.el.trigger('language_menu:show');
expect(Logger.log).toHaveBeenCalledWith('edx.video.bumper.transcript.menu.shown', {
host_component_id: 'id',
bumper_id: 'xmodule/include/fixtures/test.mp4',
bumper_id: '/base/fixtures/test.mp4',
code: 'html5',
duration: 20
});
@@ -107,7 +107,7 @@
state.el.trigger('language_menu:hide');
expect(Logger.log).toHaveBeenCalledWith('edx.video.bumper.transcript.menu.hidden', {
host_component_id: 'id',
bumper_id: 'xmodule/include/fixtures/test.mp4',
bumper_id: '/base/fixtures/test.mp4',
code: 'html5',
duration: 20
});
@@ -117,7 +117,7 @@
state.el.trigger('captions:show');
expect(Logger.log).toHaveBeenCalledWith('edx.video.bumper.transcript.shown', {
host_component_id: 'id',
bumper_id: 'xmodule/include/fixtures/test.mp4',
bumper_id: '/base/fixtures/test.mp4',
code: 'html5',
currentTime: 10,
duration: 20
@@ -128,7 +128,7 @@
state.el.trigger('captions:hide');
expect(Logger.log).toHaveBeenCalledWith('edx.video.bumper.transcript.hidden', {
host_component_id: 'id',
bumper_id: 'xmodule/include/fixtures/test.mp4',
bumper_id: '/base/fixtures/test.mp4',
code: 'html5',
currentTime: 10,
duration: 20
@@ -137,7 +137,7 @@
it('can destroy itself', function () {
var plugin = state.bumperState.videoEventsBumperPlugin;
spyOn($.fn, 'off').andCallThrough();
spyOn($.fn, 'off').and.callThrough();
plugin.destroy();
expect(state.bumperState.videoEventsBumperPlugin).toBeUndefined();
expect($.fn.off).toHaveBeenCalledWith({

View File

@@ -7,12 +7,11 @@
oldOTBD = window.onTouchBasedDevice;
window.onTouchBasedDevice = jasmine
.createSpy('onTouchBasedDevice')
.andReturn(null);
.and.returnValue(null);
jasmine.stubRequests();
state = jasmine.initializePlayer();
spyOn(Logger, 'log');
spyOn(state.videoEventsPlugin, 'getCurrentTime').andReturn(10);
spyOn(state.videoEventsPlugin, 'getCurrentTime').and.returnValue(10);
});
afterEach(function () {
@@ -90,7 +89,7 @@
});
expect(state.videoEventsPlugin.emitPlayVideoEvent).toBeTruthy();
Logger.log.reset();
Logger.log.calls.reset();
state.el.trigger('stop');
expect(Logger.log).toHaveBeenCalledWith('stop_video', {
id: 'id',
@@ -155,7 +154,7 @@
it('can destroy itself', function () {
var plugin = state.videoEventsPlugin;
spyOn($.fn, 'off').andCallThrough();
spyOn($.fn, 'off').and.callThrough();
state.videoEventsPlugin.destroy();
expect(state.videoEventsPlugin).toBeUndefined();
expect($.fn.off).toHaveBeenCalledWith({

View File

@@ -15,17 +15,19 @@
// stack.
jQuery.fx.off = true;
jasmine.stubRequests();
loadFixtures('video_html5.html');
state = new Video('#example');
spyOnEvent(state.el, 'mousemove');
spyOn(state.focusGrabber, 'disableFocusGrabber').andCallThrough();
spyOn(state.focusGrabber, 'enableFocusGrabber').andCallThrough();
spyOn(state.focusGrabber, 'disableFocusGrabber').and.callThrough();
spyOn(state.focusGrabber, 'enableFocusGrabber').and.callThrough();
});
afterEach(function () {
// Turn jQuery animations back on.
jQuery.fx.off = true;
state.storage.clear();
state.videoPlayer.destroy();
});

View File

@@ -6,7 +6,7 @@
beforeEach(function () {
oldOTBD = window.onTouchBasedDevice;
window.onTouchBasedDevice = jasmine
.createSpy('onTouchBasedDevice').andReturn(null);
.createSpy('onTouchBasedDevice').and.returnValue(null);
});
afterEach(function () {
@@ -83,7 +83,7 @@
});
it('Controls height is actual on switch to fullscreen', function () {
spyOn($.fn, 'height').andCallFake(function (val) {
spyOn($.fn, 'height').and.callFake(function (val) {
return _.isUndefined(val) ? 100: this;
});

View File

@@ -6,7 +6,7 @@
beforeEach(function () {
oldOTBD = window.onTouchBasedDevice;
window.onTouchBasedDevice = jasmine
.createSpy('onTouchBasedDevice').andReturn(null);
.createSpy('onTouchBasedDevice').and.returnValue(null);
state = jasmine.initializePlayer();
spyOn(state.videoCommands, 'execute');
spyOn(state.videoSaveStatePlugin, 'saveState');

View File

@@ -6,7 +6,7 @@
beforeEach(function () {
oldOTBD = window.onTouchBasedDevice;
window.onTouchBasedDevice = jasmine
.createSpy('onTouchBasedDevice').andReturn(['iPad']);
.createSpy('onTouchBasedDevice').and.returnValue(['iPad']);
state = jasmine.initializePlayer();
spyOn(state.videoCommands, 'execute');
@@ -41,7 +41,7 @@
beforeEach(function () {
jasmine.stubRequests();
spyOn(window.YT, 'Player').andCallThrough();
spyOn(window.YT, 'Player').and.callThrough();
});
it ('works correctly on calling proper methods', function () {
@@ -77,7 +77,7 @@
it(message, function () {
var btnPlay;
window.onTouchBasedDevice.andReturn(data.isTouch);
window.onTouchBasedDevice.and.returnValue(data.isTouch);
state = jasmine.initializePlayer();
btnPlay = state.el.find('.btn-play');
@@ -97,7 +97,7 @@
{
var btnPlay;
window.onTouchBasedDevice.andReturn([device]);
window.onTouchBasedDevice.and.returnValue([device]);
state = jasmine.initializePlayer();
btnPlay = state.el.find('.btn-play');
@@ -113,7 +113,7 @@
{
var btnPlay;
window.onTouchBasedDevice.andReturn([device]);
window.onTouchBasedDevice.and.returnValue([device]);
state = jasmine.initializePlayer();
btnPlay = state.el.find('.btn-play');
@@ -128,7 +128,7 @@
{
var btnPlay;
window.onTouchBasedDevice.andReturn([device]);
window.onTouchBasedDevice.and.returnValue([device]);
state = jasmine.initializePlayerYouTube();
btnPlay = state.el.find('.btn-play');

View File

@@ -6,7 +6,7 @@
beforeEach(function () {
oldOTBD = window.onTouchBasedDevice;
window.onTouchBasedDevice = jasmine
.createSpy('onTouchBasedDevice').andReturn(null);
.createSpy('onTouchBasedDevice').and.returnValue(null);
state = jasmine.initializePlayer('video_with_bumper.html');
$('.poster .btn-play').click();
spyOn(state.bumperState.videoCommands, 'execute');
@@ -19,16 +19,19 @@
state.bumperState.videoPlayer.destroy();
}
window.onTouchBasedDevice = oldOTBD;
if (state.videoPlayer) {
_.result(state.videoPlayer, 'destroy');
}
});
it('can render the control', function () {
expect($('.video_control.play')).toExist();
expect($('.video_control.play')).toBeInDOM();
});
it('can update state on play', function () {
state.el.trigger('play');
expect($('.video_control.play')).not.toExist();
expect($('.video_control.skip')).toExist();
expect($('.video_control.play')).not.toBeInDOM();
expect($('.video_control.skip')).toBeInDOM();
});
it('can start video playing on click', function () {
@@ -38,7 +41,7 @@
it('can skip the video on click', function () {
state.el.trigger('play');
spyOn(state.bumperState.videoPlayer, 'isPlaying').andReturn(true);
spyOn(state.bumperState.videoPlayer, 'isPlaying').and.returnValue(true);
$('.video_control.skip').first().click();
expect(state.bumperState.videoCommands.execute).toHaveBeenCalledWith('skip');
});
@@ -46,10 +49,10 @@
it('can destroy itself', function () {
var plugin = state.bumperState.videoPlaySkipControl,
el = plugin.el;
spyOn($.fn, 'off').andCallThrough();
spyOn($.fn, 'off').and.callThrough();
plugin.destroy();
expect(state.bumperState.videoPlaySkipControl).toBeUndefined();
expect(el).not.toExist();
expect(el).not.toBeInDOM();
expect($.fn.off).toHaveBeenCalledWith('destroy', plugin.destroy);
});
});

View File

@@ -5,12 +5,16 @@ require(
['video/03_video_player.js'],
function (VideoPlayer) {
describe('VideoPlayer', function () {
var state, oldOTBD;
var state, oldOTBD, empty_arguments;
(function () {
empty_arguments = arguments;
})();
beforeEach(function () {
oldOTBD = window.onTouchBasedDevice;
window.onTouchBasedDevice = jasmine.createSpy('onTouchBasedDevice')
.andReturn(null);
.and.returnValue(null);
});
afterEach(function () {
@@ -73,7 +77,7 @@ function (VideoPlayer) {
var events;
jasmine.stubRequests();
spyOn(window.YT, 'Player').andCallThrough();
spyOn(window.YT, 'Player').and.callThrough();
state = jasmine.initializePlayerYouTube();
state.videoEl = $('video, iframe');
@@ -107,9 +111,9 @@ function (VideoPlayer) {
state = jasmine.initializePlayerYouTube();
state.videoEl = state.el.find('video, iframe').width(100);
player = state.videoPlayer.player;
player.getAvailablePlaybackRates.andReturn([1]);
player.getAvailablePlaybackRates.and.returnValue([1]);
state.currentPlayerMode = 'html5';
spyOn(window.YT, 'Player').andCallThrough();
spyOn(window.YT, 'Player').and.callThrough();
state.videoPlayer.onReady();
expect(YT.Player).toHaveBeenCalledWith('id', {
@@ -137,7 +141,7 @@ function (VideoPlayer) {
describe('when on a touch based device', function () {
$.each(['iPad', 'Android'], function (index, device) {
it('create video volume control on' + device, function () {
window.onTouchBasedDevice.andReturn([device]);
window.onTouchBasedDevice.and.returnValue([device]);
state = jasmine.initializePlayer();
state.videoEl = $('video, iframe');
@@ -167,7 +171,7 @@ function (VideoPlayer) {
state = jasmine.initializePlayer();
state.videoEl = $('video, iframe');
spyOn(state.videoPlayer, 'play').andCallThrough();
spyOn(state.videoPlayer, 'play').and.callThrough();
state.videoPlayer.onReady();
});
@@ -204,7 +208,7 @@ function (VideoPlayer) {
state = jasmine.initializePlayerYouTube();
state.videoEl = $('video, iframe');
spyOn($.fn, 'trigger').andCallThrough();
spyOn($.fn, 'trigger').and.callThrough();
state.videoPlayer.onStateChange({
data: YT.PlayerState.ENDED
});
@@ -215,8 +219,8 @@ function (VideoPlayer) {
});
it('trigger pause and ended events', function () {
expect($.fn.trigger).toHaveBeenCalledWith('pause', {});
expect($.fn.trigger).toHaveBeenCalledWith('ended', {});
expect($.fn.trigger).toHaveBeenCalledWith('pause', empty_arguments);
expect($.fn.trigger).toHaveBeenCalledWith('ended', empty_arguments);
});
});
});
@@ -226,7 +230,7 @@ function (VideoPlayer) {
beforeEach(function () {
state = jasmine.initializePlayer();
state.videoEl = $('video, iframe');
spyOn($.fn, 'trigger').andCallThrough();
spyOn($.fn, 'trigger').and.callThrough();
state.videoPlayer.onStateChange({
data: YT.PlayerState.PAUSED
@@ -238,7 +242,7 @@ function (VideoPlayer) {
});
it('pause the video caption', function () {
expect($.fn.trigger).toHaveBeenCalledWith('pause', {});
expect($.fn.trigger).toHaveBeenCalledWith('pause', empty_arguments);
});
});
@@ -250,15 +254,15 @@ function (VideoPlayer) {
state = jasmine.initializePlayer();
oldState = state;
spyOn(oldState.videoPlayer, 'onPause').andCallThrough();
spyOn(oldState.videoPlayer, 'onPause').and.callThrough();
// Now initialize a second instance.
state = jasmine.initializePlayer();
state.videoEl = $('video, iframe');
spyOn(window, 'setInterval').andReturn(100);
spyOn($.fn, 'trigger').andCallThrough();
spyOn(window, 'setInterval').and.returnValue(100);
spyOn($.fn, 'trigger').and.callThrough();
state.videoPlayer.onStateChange({
data: YT.PlayerState.PLAYING
@@ -277,7 +281,7 @@ function (VideoPlayer) {
});
it('play the video caption', function () {
expect($.fn.trigger).toHaveBeenCalledWith('play', {});
expect($.fn.trigger).toHaveBeenCalledWith('play', empty_arguments);
});
});
@@ -289,7 +293,7 @@ function (VideoPlayer) {
state.videoEl = $('video, iframe');
spyOn($.fn, 'trigger').andCallThrough();
spyOn($.fn, 'trigger').and.callThrough();
state.videoPlayer.onStateChange({
data: YT.PlayerState.PLAYING
});
@@ -310,7 +314,7 @@ function (VideoPlayer) {
});
it('pause the video caption', function () {
expect($.fn.trigger).toHaveBeenCalledWith('pause', {});
expect($.fn.trigger).toHaveBeenCalledWith('pause', empty_arguments);
});
});
@@ -319,7 +323,7 @@ function (VideoPlayer) {
state = jasmine.initializePlayer();
state.videoEl = $('video, iframe');
spyOn($.fn, 'trigger').andCallThrough();
spyOn($.fn, 'trigger').and.callThrough();
state.videoPlayer.onStateChange({
data: YT.PlayerState.ENDED
});
@@ -330,7 +334,7 @@ function (VideoPlayer) {
});
it('pause the video caption', function () {
expect($.fn.trigger).toHaveBeenCalledWith('ended', {});
expect($.fn.trigger).toHaveBeenCalledWith('ended', empty_arguments);
});
});
});
@@ -362,59 +366,51 @@ function (VideoPlayer) {
describe('onSeek', function () {
beforeEach(function () {
// jasmine.Clock can't be used to fake out debounce with newer versions of underscore
spyOn(_, 'debounce').andCallFake(function (func) {
spyOn(_, 'debounce').and.callFake(function (func) {
return function () {
func.apply(this, arguments);
};
});
state = jasmine.initializePlayer();
state.videoEl = $('video, iframe');
spyOn(state.videoPlayer, 'duration').andReturn(120);
spyOn(state.videoPlayer, 'duration').and.returnValue(120);
});
describe('when the video is playing', function () {
beforeEach(function () {
runs(function () {
state.videoPlayer.play();
});
beforeEach(function (done) {
state.videoPlayer.play();
waitsFor(function () {
jasmine.waitUntil(function() {
return state.videoPlayer.isPlaying();
}, 'video didn\'t start playing', WAIT_TIMEOUT);
}).done(done);
});
it('call runTimer in seekTo on player', function () {
runs(function () {
spyOn(state.videoPlayer, 'stopTimer');
spyOn(state.videoPlayer, 'runTimer');
state.videoPlayer.seekTo(10);
expect(state.videoPlayer.currentTime).toBe(10);
expect(state.videoPlayer.stopTimer).toHaveBeenCalled();
expect(state.videoPlayer.runTimer).toHaveBeenCalled();
});
spyOn(state.videoPlayer, 'stopTimer').and.callThrough();
spyOn(state.videoPlayer, 'runTimer').and.callThrough();
state.videoPlayer.seekTo(10);
expect(state.videoPlayer.currentTime).toBe(10);
expect(state.videoPlayer.stopTimer).toHaveBeenCalled();
expect(state.videoPlayer.runTimer).toHaveBeenCalled();
});
it('seek the player', function () {
runs(function () {
spyOn(state.videoPlayer.player, 'seekTo').andCallThrough();
state.videoProgressSlider.onSlide(
jQuery.Event('slide'), { value: 30 }
);
expect(state.videoPlayer.currentTime).toBe(30);
expect(state.videoPlayer.player.seekTo).toHaveBeenCalledWith(30, true);
});
spyOn(state.videoPlayer.player, 'seekTo').and.callThrough();
state.videoProgressSlider.onSlide(
jQuery.Event('slide'), { value: 30 }
);
expect(state.videoPlayer.currentTime).toBe(30);
expect(state.videoPlayer.player.seekTo).toHaveBeenCalledWith(30, true);
});
it('call updatePlayTime on player', function () {
runs(function () {
spyOn(state.videoPlayer, 'updatePlayTime').andCallThrough();
state.videoProgressSlider.onSlide(
jQuery.Event('slide'), { value: 30 }
);
expect(state.videoPlayer.currentTime).toBe(30);
expect(state.videoPlayer.updatePlayTime).toHaveBeenCalledWith(30, true);
});
spyOn(state.videoPlayer, 'updatePlayTime').and.callThrough();
state.videoProgressSlider.onSlide(
jQuery.Event('slide'), { value: 30 }
);
expect(state.videoPlayer.currentTime).toBe(30);
expect(state.videoPlayer.updatePlayTime).toHaveBeenCalledWith(30, true);
});
});
@@ -433,7 +429,7 @@ function (VideoPlayer) {
describe('when the video is not playing', function () {
beforeEach(function () {
spyOn(state.videoPlayer, 'setPlaybackRate')
.andCallThrough();
.and.callThrough();
});
it('video has a correct speed', function () {
@@ -442,7 +438,7 @@ function (VideoPlayer) {
expect(state.videoPlayer.setPlaybackRate)
.toHaveBeenCalledWith('2.0', true);
state.videoPlayer.onPlay();
expect(state.videoPlayer.setPlaybackRate.calls.length)
expect(state.videoPlayer.setPlaybackRate.calls.count())
.toEqual(1);
});
});
@@ -483,7 +479,7 @@ function (VideoPlayer) {
state.videoEl = $('video, iframe');
spyOn(state.videoPlayer, 'updatePlayTime').andCallThrough();
spyOn(state.videoPlayer, 'updatePlayTime').and.callThrough();
});
describe(
@@ -535,29 +531,26 @@ function (VideoPlayer) {
state.videoEl = $('video, iframe');
spyOn(state.videoPlayer, 'update').andCallThrough();
spyOn(state.videoPlayer, 'pause').andCallThrough();
spyOn(state.videoPlayer, 'update').and.callThrough();
spyOn(state.videoPlayer, 'pause').and.callThrough();
spyOn(state.videoProgressSlider, 'notifyThroughHandleEnd')
.andCallThrough();
.and.callThrough();
});
it(
'video is paused on first endTime, start & end time are reset',
function ()
function (done)
{
var duration;
state.videoProgressSlider.notifyThroughHandleEnd.reset();
state.videoPlayer.pause.reset();
state.videoProgressSlider.notifyThroughHandleEnd.calls.reset();
state.videoPlayer.pause.calls.reset();
state.videoPlayer.play();
waitsFor(function () {
jasmine.waitUntil(function () {
duration = Math.round(state.videoPlayer.currentTime);
return state.videoPlayer.pause.calls.length === 1;
}, 'pause() has been called', WAIT_TIMEOUT);
runs(function () {
return state.videoPlayer.pause.calls.count() === 1;
}).then(function () {
expect(state.videoPlayer.startTime).toBe(0);
expect(state.videoPlayer.endTime).toBe(null);
@@ -565,7 +558,7 @@ function (VideoPlayer) {
expect(state.videoProgressSlider.notifyThroughHandleEnd)
.toHaveBeenCalledWith({end: true});
});
}).always(done);
});
});
@@ -573,14 +566,14 @@ function (VideoPlayer) {
beforeEach(function () {
state = jasmine.initializePlayerYouTube();
state.videoEl = $('video, iframe');
spyOn(state.videoCaption, 'updatePlayTime').andCallThrough();
spyOn(state.videoProgressSlider, 'updatePlayTime').andCallThrough();
spyOn(state.videoCaption, 'updatePlayTime').and.callThrough();
spyOn(state.videoProgressSlider, 'updatePlayTime').and.callThrough();
});
it('update the video playback time', function () {
it('update the video playback time', function (done) {
var duration = 0;
waitsFor(function () {
jasmine.waitUntil(function () {
duration = state.videoPlayer.duration();
if (duration > 0) {
@@ -588,40 +581,34 @@ function (VideoPlayer) {
}
return false;
}, 'Video is fully loaded.', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
state.videoPlayer.goToStartTime = false;
state.videoPlayer.updatePlayTime(60);
expect($('.vidtime')).toHaveHtml('1:00 / 1:00');
});
}).always(done);
});
it('update the playback time on caption', function () {
waitsFor(function () {
it('update the playback time on caption', function (done) {
jasmine.waitUntil(function () {
return state.videoPlayer.duration() > 0;
}, 'Video is fully loaded.', WAIT_TIMEOUT);
runs(function () {
}, 1000).then(function () {
state.videoPlayer.goToStartTime = false;
state.videoPlayer.updatePlayTime(60);
expect(state.videoCaption.updatePlayTime)
.toHaveBeenCalledWith(60);
});
}).always(done);
});
it('update the playback time on progress slider', function () {
it('update the playback time on progress slider', function (done) {
var duration = 0;
waitsFor(function () {
jasmine.waitUntil(function () {
duration = state.videoPlayer.duration();
return duration > 0;
}, 'Video is fully loaded.', WAIT_TIMEOUT);
runs(function () {
}, 1000).then(function () {
state.videoPlayer.goToStartTime = false;
state.videoPlayer.updatePlayTime(60);
@@ -630,7 +617,7 @@ function (VideoPlayer) {
time: 60,
duration: duration
});
});
}).always(done);
});
});
@@ -652,15 +639,15 @@ function (VideoPlayer) {
state.videoEl = $('video, iframe');
spyOn(state.videoPlayer, 'updatePlayTime').andCallThrough();
spyOn(state.videoPlayer.player, 'seekTo').andCallThrough();
spyOn(state.videoPlayer, 'updatePlayTime').and.callThrough();
spyOn(state.videoPlayer.player, 'seekTo').and.callThrough();
spyOn(state.videoProgressSlider, 'updateStartEndTimeRegion')
.andCallThrough();
.and.callThrough();
});
it(
'when duration becomes available, updatePlayTime() is called',
function ()
function (done)
{
var duration;
@@ -669,14 +656,12 @@ function (VideoPlayer) {
state.videoPlayer.play();
waitsFor(function () {
jasmine.waitUntil(function () {
duration = state.videoPlayer.duration();
return state.videoPlayer.isPlaying() &&
state.videoPlayer.initialSeekToStartTime === false;
}, 'duration becomes available', WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expect(state.videoPlayer.startTime).toBe(START_TIME);
expect(state.videoPlayer.endTime).toBe(END_TIME);
@@ -688,7 +673,7 @@ function (VideoPlayer) {
expect(state.videoPlayer.seekToStartTimeOldSpeed)
.toBe(state.speed);
});
}).always(done);
});
});
@@ -708,7 +693,7 @@ function (VideoPlayer) {
seekTo: function () {}
},
figureOutStartEndTime: jasmine.createSpy(),
figureOutStartingTime: jasmine.createSpy().andReturn(0)
figureOutStartingTime: jasmine.createSpy().and.returnValue(0)
},
config: {
savedVideoPosition: 0,
@@ -723,7 +708,7 @@ function (VideoPlayer) {
currentPlayerMode: 'html5',
trigger: function () {},
browserIsFirefox: false,
isFlashMode: jasmine.createSpy().andReturn(false)
isFlashMode: jasmine.createSpy().and.returnValue(false)
};
});
});
@@ -733,7 +718,7 @@ function (VideoPlayer) {
beforeEach(function () {
state = jasmine.initializePlayer();
state.videoEl = $('video, iframe');
spyOn($.fn, 'trigger').andCallThrough();
spyOn($.fn, 'trigger').and.callThrough();
$('.add-fullscreen').click();
});
@@ -752,7 +737,7 @@ function (VideoPlayer) {
beforeEach(function () {
state = jasmine.initializePlayer();
state.videoEl = $('video, iframe');
spyOn($.fn, 'trigger').andCallThrough();
spyOn($.fn, 'trigger').and.callThrough();
state.el.addClass('video-fullscreen');
state.videoFullScreen.fullScreenState = true;
state.videoFullScreen.isFullScreen = true;
@@ -779,7 +764,7 @@ function (VideoPlayer) {
state.videoEl = $('video, iframe');
spyOn(state.videoPlayer.player, 'getDuration').andCallThrough();
spyOn(state.videoPlayer.player, 'getDuration').and.callThrough();
state.videoPlayer.duration();
});
@@ -801,11 +786,11 @@ function (VideoPlayer) {
state.videoEl = $('video, iframe');
spyOn(state, 'getDuration').andCallThrough();
spyOn(state, 'getDuration').and.callThrough();
// When `state.videoPlayer.player.getDuration()` returns a `0`,
// the fall-back function `state.getDuration()` will be called.
state.videoPlayer.player.getDuration.andReturn(0);
state.videoPlayer.player.getDuration.and.returnValue(0);
});
it('getDuration is called as a fall-back', function () {
@@ -821,7 +806,7 @@ function (VideoPlayer) {
state.videoEl = $('video, iframe');
spyOn(state.videoPlayer.player, 'getVolume').andCallThrough();
spyOn(state.videoPlayer.player, 'getVolume').and.callThrough();
});
it('set the player volume', function () {
@@ -841,7 +826,7 @@ function (VideoPlayer) {
['iPad', 'Android', 'iPhone'],
function (index, device)
{
window.onTouchBasedDevice.andReturn([device]);
window.onTouchBasedDevice.and.returnValue([device]);
state = jasmine.initializePlayer();
state.videoEl = $('video, iframe');
@@ -851,7 +836,7 @@ function (VideoPlayer) {
});
it('modules are not initialized on iPhone', function () {
window.onTouchBasedDevice.andReturn(['iPhone']);
window.onTouchBasedDevice.and.returnValue(['iPhone']);
state = jasmine.initializePlayer();
state.videoEl = $('video, iframe');
@@ -870,34 +855,28 @@ function (VideoPlayer) {
var message = 'controls become visible after playing starts ' +
'on ' + device;
it(message, function () {
it(message, function (done) {
var controls;
window.onTouchBasedDevice.andReturn([device]);
window.onTouchBasedDevice.and.returnValue([device]);
runs(function () {
state = jasmine.initializePlayer();
state.videoEl = $('video, iframe');
controls = state.el.find('.video-controls');
});
state = jasmine.initializePlayer();
state.videoEl = $('video, iframe');
controls = state.el.find('.video-controls');
waitsFor(function () {
jasmine.waitUntil(function () {
return state.el.hasClass('is-initialized');
},'Video is not initialized.' , WAIT_TIMEOUT);
runs(function () {
}).then(function () {
expect(controls).toHaveClass('is-hidden');
state.videoPlayer.play();
});
waitsFor(function () {
var duration = state.videoPlayer.duration();
return duration > 0 && state.videoPlayer.isPlaying();
},'Video does not play.' , WAIT_TIMEOUT);
runs(function () {
expect(controls).not.toHaveClass('is-hidden');
jasmine.waitUntil(function () {
// Firefox does not return duration for videos until they have reached the end.
// var duration = state.videoPlayer.duration();
// return duration > 0 && state.videoPlayer.isPlaying();
return state.videoPlayer.isPlaying();
}).then(function () {
expect(controls).not.toHaveClass('is-hidden');
}).always(done);
});
});
});
@@ -916,13 +895,13 @@ function (VideoPlayer) {
setPlaybackRate: jasmine.createSpy(),
player: jasmine.createSpyObj('player', ['setPlaybackRate'])
},
isFlashMode: jasmine.createSpy().andReturn(false)
isFlashMode: jasmine.createSpy().and.returnValue(false)
};
});
describe('always', function () {
it('convert the current time to the new speed', function () {
state.isFlashMode.andReturn(true);
state.isFlashMode.and.returnValue(true);
VideoPlayer.prototype.onSpeedChange.call(state, '0.75', false);
expect(state.videoPlayer.currentTime).toBe('120.000');
});
@@ -939,17 +918,17 @@ function (VideoPlayer) {
describe('setPlaybackRate', function () {
beforeEach(function () {
state = {
youtubeId: jasmine.createSpy().andReturn('videoId'),
isFlashMode: jasmine.createSpy().andReturn(false),
isHtml5Mode: jasmine.createSpy().andReturn(true),
isYoutubeType: jasmine.createSpy().andReturn(true),
youtubeId: jasmine.createSpy().and.returnValue('videoId'),
isFlashMode: jasmine.createSpy().and.returnValue(false),
isHtml5Mode: jasmine.createSpy().and.returnValue(true),
isYoutubeType: jasmine.createSpy().and.returnValue(true),
setPlayerMode: jasmine.createSpy(),
trigger: jasmine.createSpy(),
videoPlayer: {
currentTime: 60,
isPlaying: jasmine.createSpy(),
seekTo: jasmine.createSpy(),
duration: jasmine.createSpy().andReturn(60),
duration: jasmine.createSpy().and.returnValue(60),
updatePlayTime: jasmine.createSpy(),
setPlaybackRate: jasmine.createSpy(),
player: jasmine.createSpyObj('player', [
@@ -960,9 +939,9 @@ function (VideoPlayer) {
});
it('in Flash mode and video is playing', function () {
state.isFlashMode.andReturn(true);
state.isHtml5Mode.andReturn(false);
state.videoPlayer.isPlaying.andReturn(true);
state.isFlashMode.and.returnValue(true);
state.isHtml5Mode.and.returnValue(false);
state.videoPlayer.isPlaying.and.returnValue(true);
VideoPlayer.prototype.setPlaybackRate.call(state, '0.75');
expect(state.videoPlayer.updatePlayTime).toHaveBeenCalledWith(60);
expect(state.videoPlayer.player.loadVideoById)
@@ -970,9 +949,9 @@ function (VideoPlayer) {
});
it('in Flash mode and video not started', function () {
state.isFlashMode.andReturn(true);
state.isHtml5Mode.andReturn(false);
state.videoPlayer.isPlaying.andReturn(false);
state.isFlashMode.and.returnValue(true);
state.isHtml5Mode.and.returnValue(false);
state.videoPlayer.isPlaying.and.returnValue(false);
VideoPlayer.prototype.setPlaybackRate.call(state, '0.75');
expect(state.videoPlayer.updatePlayTime).toHaveBeenCalledWith(60);
expect(state.videoPlayer.seekTo).toHaveBeenCalledWith(60);
@@ -986,7 +965,7 @@ function (VideoPlayer) {
});
it('in HTML5 mode', function () {
state.isYoutubeType.andReturn(false);
state.isYoutubeType.and.returnValue(false);
VideoPlayer.prototype.setPlaybackRate.call(state, '0.75');
expect(state.videoPlayer.player.setPlaybackRate).toHaveBeenCalledWith('0.75');
});
@@ -994,7 +973,7 @@ function (VideoPlayer) {
it('Youtube video in FF, with new speed equal 1.0', function () {
state.browserIsFirefox = true;
state.videoPlayer.isPlaying.andReturn(false);
state.videoPlayer.isPlaying.and.returnValue(false);
VideoPlayer.prototype.setPlaybackRate.call(state, '1.0');
expect(state.videoPlayer.updatePlayTime).toHaveBeenCalledWith(60);
expect(state.videoPlayer.player.cueVideoById)

View File

@@ -6,7 +6,7 @@
beforeEach(function () {
oldOTBD = window.onTouchBasedDevice;
window.onTouchBasedDevice = jasmine
.createSpy('onTouchBasedDevice').andReturn(null);
.createSpy('onTouchBasedDevice').and.returnValue(null);
state = jasmine.initializePlayer('video_with_bumper.html');
});
@@ -27,11 +27,11 @@
expect($('.btn-play')).toExist();
});
it('can start playing the video on click', function () {
it('can start playing the video on click', function (done) {
$('.btn-play').click();
waitsFor(function () {
jasmine.waitUntil(function() {
return state.el.hasClass('is-playing');
}, 'Player is not playing.', WAIT_TIMEOUT);
}).done(done);
});
it('destroy itself on "play" event', function () {

View File

@@ -5,7 +5,7 @@
beforeEach(function () {
oldOTBD = window.onTouchBasedDevice;
window.onTouchBasedDevice = jasmine.createSpy('onTouchBasedDevice')
.andReturn(null);
.and.returnValue(null);
});
afterEach(function () {
@@ -18,26 +18,25 @@
describe('constructor', function () {
describe('on a non-touch based device', function () {
beforeEach(function () {
spyOn($.fn, 'slider').andCallThrough();
spyOn($.fn, 'slider').and.callThrough();
state = jasmine.initializePlayer();
});
it('build the slider', function () {
expect(state.videoProgressSlider.slider).toBe('.slider');
expect($('.slider')).toContain(state.videoProgressSlider.slider);
expect($.fn.slider).toHaveBeenCalledWith({
range: 'min',
min: 0,
max: null,
change: state.videoProgressSlider.onChange,
slide: state.videoProgressSlider.onSlide,
stop: state.videoProgressSlider.onStop
});
});
it('build the seek handle', function () {
expect(state.videoProgressSlider.handle)
.toBe('.slider .ui-slider-handle');
expect($('.ui-slider-handle'))
.toContain(state.videoProgressSlider.handle);
});
it('add ARIA attributes to time control', function () {
@@ -56,7 +55,7 @@
describe('on a touch-based device', function () {
it('does not build the slider on iPhone', function () {
window.onTouchBasedDevice.andReturn(['iPhone']);
window.onTouchBasedDevice.and.returnValue(['iPhone']);
state = jasmine.initializePlayer();
@@ -67,7 +66,7 @@
});
$.each(['iPad', 'Android'], function (index, device) {
it('build the slider on ' + device, function () {
window.onTouchBasedDevice.andReturn([device]);
window.onTouchBasedDevice.and.returnValue([device]);
state = jasmine.initializePlayer();
@@ -87,12 +86,12 @@
beforeEach(function () {
spy = spyOn(state.videoProgressSlider, 'buildSlider');
spy.andCallThrough();
spy.and.callThrough();
state.videoPlayer.play();
});
it('does not build the slider', function () {
expect(spy.callCount).toEqual(0);
expect(spy.calls.count()).toEqual(0);
});
});
@@ -106,7 +105,7 @@
describe('when frozen', function () {
beforeEach(function () {
spyOn($.fn, 'slider').andCallThrough();
spyOn($.fn, 'slider').and.callThrough();
state.videoProgressSlider.frozen = true;
state.videoProgressSlider.updatePlayTime(20, 120);
});
@@ -118,7 +117,7 @@
describe('when not frozen', function () {
beforeEach(function () {
spyOn($.fn, 'slider').andCallThrough();
spyOn($.fn, 'slider').and.callThrough();
state.videoProgressSlider.frozen = false;
state.videoProgressSlider.updatePlayTime({
time: 20,
@@ -149,8 +148,8 @@
beforeEach(function () {
state = jasmine.initializePlayer();
spyOn($.fn, 'slider').andCallThrough();
spyOn(state.videoPlayer, 'onSlideSeek').andCallThrough();
spyOn($.fn, 'slider').and.callThrough();
spyOn(state.videoPlayer, 'onSlideSeek').and.callThrough();
});
// Disabled 12/30/13 due to flakiness in master
@@ -175,11 +174,15 @@
describe('onStop', function () {
beforeEach(function () {
jasmine.Clock.useMock();
jasmine.clock().install();
state = jasmine.initializePlayer();
spyOn(state.videoPlayer, 'onSlideSeek').andCallThrough();
spyOn(state.videoPlayer, 'onSlideSeek').and.callThrough();
});
afterEach(function () {
jasmine.clock().uninstall();
});
// Disabled 12/30/13 due to flakiness in master
@@ -206,7 +209,7 @@
jQuery.Event('stop'), { value: 20 }
);
jasmine.Clock.tick(200);
jasmine.clock().tick(200);
expect(state.videoProgressSlider.frozen).toBeFalsy();
});
@@ -255,7 +258,7 @@
spyOnEvent(state.videoProgressSlider.handle, 'focus');
spyOn(state.videoProgressSlider, 'notifyThroughHandleEnd')
.andCallThrough();
.and.callThrough();
});
it('params.end = true', function () {
@@ -280,17 +283,14 @@
);
});
it('is called when video plays', function () {
it('is called when video plays', function (done) {
state.videoPlayer.play();
waitsFor(function () {
jasmine.waitUntil(function() {
return state.videoPlayer.isPlaying();
}, 'duration is set, video is playing', 5000);
}).done(function() {
expect(state.videoProgressSlider.notifyThroughHandleEnd).toHaveBeenCalledWith({end: false});
}).always(done);
runs(function () {
expect(state.videoProgressSlider.notifyThroughHandleEnd)
.toHaveBeenCalledWith({end: false});
});
});
});

View File

@@ -19,7 +19,7 @@
// Define empty methods in YouTube stub
player.quality = 'large';
player.setPlaybackQuality.andCallFake(function (quality){
player.setPlaybackQuality.and.callFake(function (quality){
player.quality = quality;
});
});
@@ -46,13 +46,13 @@
});
it('calls fetchAvailableQualities only once', function () {
expect(player.getAvailableQualityLevels.calls.length)
expect(player.getAvailableQualityLevels.calls.count())
.toEqual(0);
videoPlayer.onPlay();
videoPlayer.onPlay();
expect(player.getAvailableQualityLevels.calls.length)
expect(player.getAvailableQualityLevels.calls.count())
.toEqual(1);
});
@@ -71,7 +71,7 @@
it('leaves quality control hidden on play if HD is not available',
function () {
player.getAvailableQualityLevels.andReturn(
player.getAvailableQualityLevels.and.returnValue(
['large', 'medium', 'small']
);
@@ -94,7 +94,7 @@
it('quality control is active if HD is available',
function () {
player.getAvailableQualityLevels.andReturn(
player.getAvailableQualityLevels.and.returnValue(
['highres', 'hd1080', 'hd720']
);

View File

@@ -7,14 +7,14 @@
oldOTBD = window.onTouchBasedDevice;
window.onTouchBasedDevice = jasmine
.createSpy('onTouchBasedDevice')
.andReturn(null);
.and.returnValue(null);
jasmine.stubRequests();
state = jasmine.initializePlayer();
spyOn(state.storage, 'setItem');
});
afterEach(function () {
$('source').remove();
window.onTouchBasedDevice = oldOTBD;
state.storage.clear();
@@ -41,7 +41,7 @@
beforeEach(function () {
state.videoPlayer.currentTime = videoPlayerCurrentTime;
spyOn(Time, 'formatFull').andCallThrough();
spyOn(window.Time, 'formatFull').and.callThrough();
});
it('data is not an object, async is true', function () {
@@ -172,7 +172,7 @@
});
it('can save state on page unload', function () {
$.ajax.reset();
$.ajax.calls.reset();
state.videoSaveStatePlugin.onUnload();
expect($.ajax).toHaveBeenCalledWith({
url: state.config.saveStateUrl,
@@ -212,7 +212,7 @@
it('can destroy itself', function () {
var plugin = state.videoSaveStatePlugin;
spyOn($.fn, 'off').andCallThrough();
spyOn($.fn, 'off').and.callThrough();
state.videoSaveStatePlugin.destroy();
expect(state.videoSaveStatePlugin).toBeUndefined();
expect($.fn.off).toHaveBeenCalledWith({

View File

@@ -6,10 +6,10 @@
beforeEach(function () {
oldOTBD = window.onTouchBasedDevice;
window.onTouchBasedDevice = jasmine
.createSpy('onTouchBasedDevice').andReturn(null);
.createSpy('onTouchBasedDevice').and.returnValue(null);
state = jasmine.initializePlayer('video_with_bumper.html');
$('.poster .btn-play').click();
spyOn(state.bumperState.videoCommands, 'execute').andCallThrough();
spyOn(state.bumperState.videoCommands, 'execute').and.callThrough();
});
afterEach(function () {

View File

@@ -6,7 +6,7 @@
beforeEach(function () {
oldOTBD = window.onTouchBasedDevice;
window.onTouchBasedDevice = jasmine.createSpy('onTouchBasedDevice')
.andReturn(null);
.and.returnValue(null);
});
afterEach(function () {
@@ -26,8 +26,8 @@
var secondaryControls = $('.secondary-controls'),
li = secondaryControls.find('.video-speeds li');
expect(secondaryControls).toContain('.speeds');
expect(secondaryControls).toContain('.video-speeds');
expect(secondaryControls).toContainElement('.speeds');
expect(secondaryControls).toContainElement('.video-speeds');
expect(secondaryControls.find('.value').text())
.toBe('1.50x');
expect(li.filter('.is-active')).toHaveData(
@@ -36,9 +36,7 @@
expect(li.length).toBe(state.speeds.length);
$.each(li.toArray().reverse(), function (index, link) {
expect($(link)).toHaveData(
'speed', state.speeds[index]
);
expect($(link).attr('data-speed')).toEqual(state.speeds[index]);
expect($(link).find('.speed-option').text()).toBe(
state.speeds[index] + 'x'
);
@@ -49,7 +47,7 @@
describe('when running on touch based device', function () {
$.each(['iPad', 'Android'], function (index, device) {
it('is not rendered on' + device, function () {
window.onTouchBasedDevice.andReturn([device]);
window.onTouchBasedDevice.and.returnValue([device]);
state = jasmine.initializePlayer();
expect(state.el.find('.speeds')).not.toExist();

View File

@@ -19,7 +19,7 @@ function (VideoStorage) {
});
it('without namespace and id', function () {
spyOn(Number.prototype, 'toString').andReturn('0.abcdedg');
spyOn(Number.prototype, 'toString').and.returnValue('0.abcdedg');
var storage = VideoStorage();
expect(window.VideoStorage).toBeDefined();

Some files were not shown because too many files have changed in this diff Show More