Commit 9cbfea2e by muzaffaryousaf Committed by Usman Khalid

Js test fixes for common, common-requirejs, xmodule.

parent 375f2bfc
......@@ -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>
......
......@@ -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>
......
......@@ -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>
......
......@@ -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>
......
......@@ -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>
......
......@@ -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">
......
......@@ -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
......
......@@ -37,6 +37,7 @@ var files = [
{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},
......
......@@ -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');
......
(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;
......
......@@ -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')
......
......@@ -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)
......
......@@ -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()
......
......@@ -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);
});
});
});
......
......@@ -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 () {
......
......@@ -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();
});
......
......@@ -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);
......
......@@ -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();
});
});
......
......@@ -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();
});
......
......@@ -3,19 +3,19 @@
describe('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});
});
......
......@@ -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
......
(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({
......
......@@ -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({
......
......@@ -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();
});
......
......@@ -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;
});
......
......@@ -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');
......
......@@ -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');
......
......@@ -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);
});
});
......
......@@ -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 () {
......
......@@ -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});
});
});
});
......
......@@ -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']
);
......
......@@ -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({
......
......@@ -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 () {
......
......@@ -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();
......
......@@ -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();
......
......@@ -12,7 +12,7 @@ describe('VideoVolumeControl', function () {
beforeEach(function () {
oldOTBD = window.onTouchBasedDevice;
window.onTouchBasedDevice = jasmine.createSpy('onTouchBasedDevice')
.andReturn(null);
.and.returnValue(null);
});
afterEach(function () {
......@@ -23,7 +23,7 @@ describe('VideoVolumeControl', function () {
});
it('Volume level has correct value even if cookie is broken', function () {
$.cookie.andReturn('broken_cookie');
$.cookie.and.returnValue('broken_cookie');
state = jasmine.initializePlayer();
volumeControl = state.videoVolumeControl;
expect(volumeControl.volume).toEqual(100);
......@@ -31,8 +31,8 @@ describe('VideoVolumeControl', function () {
describe('constructor', function () {
beforeEach(function () {
spyOn($.fn, 'slider').andCallThrough();
$.cookie.andReturn('75');
spyOn($.fn, 'slider').and.callThrough();
$.cookie.and.returnValue('75');
state = jasmine.initializePlayer();
volumeControl = state.videoVolumeControl;
});
......@@ -46,7 +46,7 @@ describe('VideoVolumeControl', function () {
});
it('create the slider', function () {
expect($.fn.slider.calls[2].args).toEqual([{
expect($.fn.slider.calls.argsFor(2)).toEqual([{
orientation: 'vertical',
range: 'min',
min: 0,
......@@ -94,16 +94,23 @@ describe('VideoVolumeControl', function () {
state = jasmine.initializePlayer();
volumeControl = state.videoVolumeControl;
this.addMatchers({
assertLiveRegionState: function (volume, expectation) {
var region = $('.video-live-region');
jasmine.addMatchers({
assertLiveRegionState: function () {
return {
compare: function (actual, volume, expectation) {
var region = $('.video-live-region');
var getExpectedText = function (text) {
return text + ' Volume.';
};
var getExpectedText = function (text) {
return text + ' Volume.';
};
actual.setVolume(volume, true, true);
return {
pass: region.text() === getExpectedText(expectation)
};
this.actual.setVolume(volume, true, true);
return region.text() === getExpectedText(expectation);
}
};
}
});
});
......
......@@ -36,7 +36,7 @@
window.Video = jasmine.createSpy('Video');
removeVideo = true;
}
window.Video.andReturn(videoModule);
window.Video.and.returnValue(videoModule);
editCallback = jasmine.createSpy('editCallback');
$(document).on('XModule.loaded.edit', editCallback);
......@@ -171,7 +171,7 @@
el = 'dummy object';
obj = new XModule.Descriptor(el);
spyOn(obj, 'save').andCallThrough();
spyOn(obj, 'save').and.callThrough();
});
afterEach(function () {
......@@ -225,7 +225,7 @@
obj.onUpdate(callback1);
obj.onUpdate(callback2);
obj.save.andReturn(testValue);
obj.save.and.returnValue(testValue);
obj.update();
expect(callback1).toHaveBeenCalledWith(testValue);
......
......@@ -13,7 +13,7 @@ class @DiscussionSpecHelper
DiscussionUtil.roleIds["Moderator"].push(parseInt(DiscussionUtil.getUser().id))
@makeAjaxSpy = (fakeAjax) ->
spyOn($, "ajax").andCallFake(
spyOn($, "ajax").and.callFake(
(params) ->
fakeAjax(params)
{always: ->}
......
......@@ -6,8 +6,8 @@ describe 'DiscussionUtil', ->
it "calls through to safeAjax with correct params, and reverts the model in case of failure", ->
deferred = $.Deferred()
spyOn($, "ajax").andReturn(deferred)
spyOn(DiscussionUtil, "safeAjax").andCallThrough()
spyOn($, "ajax").and.returnValue(deferred)
spyOn(DiscussionUtil, "safeAjax").and.callThrough()
model = new Backbone.Model({hello: false, number: 42})
updates = {hello: "world"}
......@@ -19,7 +19,7 @@ describe 'DiscussionUtil', ->
# the error message callback should be set up correctly
spyOn(DiscussionUtil, "discussionAlert")
DiscussionUtil.safeAjax.mostRecentCall.args[0].error()
DiscussionUtil.safeAjax.calls.mostRecent().args[0].error()
expect(DiscussionUtil.discussionAlert).toHaveBeenCalledWith("Sorry", "error message")
# if the ajax call ends in failure, the model state should be reverted
......@@ -27,7 +27,7 @@ describe 'DiscussionUtil', ->
expect(model.attributes).toEqual({hello: false, number: 42})
it "rolls back the changes if the associated element is disabled", ->
spyOn(DiscussionUtil, "safeAjax").andCallThrough()
spyOn(DiscussionUtil, "safeAjax").and.callThrough()
model = new Backbone.Model({hello: false, number: 42})
updates = {hello: "world"}
......@@ -35,7 +35,7 @@ describe 'DiscussionUtil', ->
# This is the element that is disabled/enabled while the ajax request is
# in progress
$elem = jasmine.createSpyObj('$elem', ['attr'])
$elem.attr.andReturn(true)
$elem.attr.and.returnValue(true)
res = DiscussionUtil.updateWithUndo(model, updates, {foo: "bar", $elem:$elem}, "error message")
......
......@@ -27,7 +27,7 @@
});
testUpdate = function(view, thread, newTopicId, newTopicName) {
spyOn($, 'ajax').andCallFake(function(params) {
spyOn($, 'ajax').and.callFake(function(params) {
expect(params.url.path()).toEqual(DiscussionUtil.urlFor('update_thread', 'dummy_id'));
expect(params.data.thread_type).toBe('discussion');
expect(params.data.commentable_id).toBe(newTopicId);
......@@ -35,7 +35,10 @@
params.success();
return {always: function() {}};
});
view.$el.find('a.topic-title[data-discussion-id="'+newTopicId+'"]').click(); // set new topic
view.$el.find('a.topic-title').filter(function (idx, el) {
return $(el).data('discussionId') === newTopicId;
}).click(); // set new topic
view.$('.edit-post-title').val('changed thread title'); // set new title
view.$("label[for$='post-type-discussion']").click(); // set new thread type
view.$('.post-update').click();
......@@ -62,7 +65,7 @@
testCancel = function(view) {
view.$('.post-cancel').click();
expect($('.edit-post-form')).not.toExist();
}
};
it('can close the view in tab mode', function() {
this.createEditView();
......@@ -104,11 +107,11 @@
it('can save new data correctly for current discussion id with dots', function () {
this.createEditView({topicId: "6.00.1x_General"});
testUpdate(this.view, this.thread, "6>00'1x\"Basic_Question", "Basic Question");
testUpdate(this.view, this.thread, "6>00\'1x\"Basic_Question", "Basic Question");
});
it('can save new data correctly for current discussion id with special characters', function () {
this.createEditView({topicId: "6>00'1x\"Basic_Question"});
this.createEditView({topicId: "6>00\'1x\"Basic_Question"});
testUpdate(this.view, this.thread, "6.00.1x_General", "General");
});
});
......
......@@ -131,8 +131,8 @@ describe "DiscussionThreadListView", ->
created_at: '2013-04-03T20:05:39Z',
}),
]
spyOn($, "ajax")
deferred = $.Deferred()
spyOn($, "ajax").and.returnValue(deferred);
@discussion = new Discussion([])
@view = new DiscussionThreadListView(
......@@ -143,7 +143,7 @@ describe "DiscussionThreadListView", ->
@view.render()
setupAjax = (callback) ->
$.ajax.andCallFake(
$.ajax.and.callFake(
(params) =>
if callback
callback(params)
......@@ -162,7 +162,7 @@ describe "DiscussionThreadListView", ->
)
expectFilter = (filterVal) ->
$.ajax.andCallFake((params) ->
$.ajax.and.callFake((params) ->
_.each(["unread", "unanswered", "flagged"], (paramName)->
if paramName == filterVal
expect(params.data[paramName]).toEqual(true)
......@@ -199,7 +199,7 @@ describe "DiscussionThreadListView", ->
expectedGroupId = optionInfo.expectedGroupId
@view.$(".forum-nav-filter-cohort-control").val(optionInfo.val).change()
expect($.ajax).toHaveBeenCalled()
$.ajax.reset()
$.ajax.calls.reset()
)
it "search should clear filter", ->
......@@ -255,7 +255,7 @@ describe "DiscussionThreadListView", ->
sorted_threads = [threads[0], threads[3], threads[2], threads[1]]
else if new_type == 'votes'
sorted_threads = [threads[3], threads[0], threads[1], threads[2]]
$.ajax.andCallFake((params) =>
$.ajax.and.callFake((params) =>
params.success(
{"discussion_data":sorted_threads, page:1, num_pages:1}
)
......@@ -307,7 +307,7 @@ describe "DiscussionThreadListView", ->
testCorrection = (view, correctedText) ->
spyOn(view, "addSearchAlert")
$.ajax.andCallFake(
$.ajax.and.callFake(
(params) =>
params.success(
{discussion_data: [], page: 42, num_pages: 99, corrected_text: correctedText}, 'success'
......@@ -319,13 +319,13 @@ describe "DiscussionThreadListView", ->
it "adds a search alert when an alternate term was searched", ->
testCorrection(@view, "foo")
expect(@view.addSearchAlert.callCount).toEqual(1)
expect(@view.addSearchAlert.mostRecentCall.args[0]).toMatch(/foo/)
expect(@view.addSearchAlert.calls.count()).toEqual(1)
expect(@view.addSearchAlert.calls.mostRecent().args[0]).toMatch(/foo/)
it "does not add a search alert when no alternate term was searched", ->
testCorrection(@view, null)
expect(@view.addSearchAlert.callCount).toEqual(1)
expect(@view.addSearchAlert.mostRecentCall.args[0]).toMatch(/no threads matched/i)
expect(@view.addSearchAlert.calls.count()).toEqual(1)
expect(@view.addSearchAlert.calls.mostRecent().args[0]).toMatch(/no threads matched/i)
it "clears search alerts when a new search is performed", ->
spyOn(@view, "clearSearchAlerts")
......@@ -356,7 +356,7 @@ describe "DiscussionThreadListView", ->
describe "username search", ->
it "makes correct ajax calls", ->
$.ajax.andCallFake(
$.ajax.and.callFake(
(params) =>
expect(params.data.username).toEqual("testing-username")
expect(params.url.path()).toEqual(DiscussionUtil.urlFor("users"))
......@@ -371,7 +371,7 @@ describe "DiscussionThreadListView", ->
setAjaxResults = (threadSuccess, userResult) ->
# threadSuccess is a boolean indicating whether the thread search ajax call should succeed
# userResult is the value that should be returned as data from the username search ajax call
$.ajax.andCallFake(
$.ajax.and.callFake(
(params) =>
if params.data.text and threadSuccess
params.success(
......@@ -387,14 +387,14 @@ describe "DiscussionThreadListView", ->
)
it "gets called after a thread search succeeds", ->
spyOn(@view, "searchForUser").andCallThrough()
spyOn(@view, "searchForUser").and.callThrough()
setAjaxResults(true, [])
@view.searchFor("gizmo")
expect(@view.searchForUser).toHaveBeenCalled()
expect($.ajax.mostRecentCall.args[0].data.username).toEqual("gizmo")
expect($.ajax.calls.mostRecent().args[0].data.username).toEqual("gizmo")
it "does not get called after a thread search fails", ->
spyOn(@view, "searchForUser").andCallThrough()
spyOn(@view, "searchForUser").and.callThrough()
setAjaxResults(false, [])
@view.searchFor("gizmo")
expect(@view.searchForUser).not.toHaveBeenCalled()
......@@ -405,7 +405,7 @@ describe "DiscussionThreadListView", ->
@view.searchForUser("dummy")
expect($.ajax).toHaveBeenCalled()
expect(@view.addSearchAlert).toHaveBeenCalled()
expect(@view.addSearchAlert.mostRecentCall.args[0]).toMatch(/gizmo/)
expect(@view.addSearchAlert.calls.mostRecent().args[0]).toMatch(/gizmo/)
it "does not add a search alert when no username was matched", ->
spyOn(@view, "addSearchAlert")
......@@ -581,7 +581,7 @@ describe "DiscussionThreadListView", ->
,
"Following"
)
expect($.ajax.mostRecentCall.args[0].data.group_id).toBeUndefined();
expect($.ajax.calls.mostRecent().args[0].data.group_id).toBeUndefined();
it "should get threads for the selected leaf", ->
testSelectionRequest(
......
......@@ -27,7 +27,7 @@ describe "DiscussionThreadProfileView", ->
return thread
spyConvertMath = (view) ->
spyOn(view, "convertMath").andCallFake( ->
spyOn(view, "convertMath").and.callFake( ->
@model.set('markdownBody', @model.get('body'))
)
......
......@@ -22,7 +22,7 @@ describe "DiscussionThreadShowView", ->
@thread = new Thread(@threadData)
@view = new DiscussionThreadShowView({ model: @thread })
@view.setElement($("#fixture-element"))
@spyOn(@view, "convertMath")
spyOn(@view, "convertMath")
describe "voting", ->
......
......@@ -3,11 +3,12 @@ describe "DiscussionThreadView", ->
DiscussionSpecHelper.setUpGlobals()
DiscussionSpecHelper.setUnderscoreFixtures()
jasmine.Clock.useMock()
jasmine.clock().install()
@threadData = DiscussionViewSpecHelper.makeThreadWithProps({})
@thread = new Thread(@threadData)
@discussion = new Discussion(@thread)
spyOn($, "ajax")
deferred = $.Deferred();
spyOn($, "ajax").and.returnValue(deferred);
# Avoid unnecessary boilerplate
spyOn(DiscussionThreadShowView.prototype, "convertMath")
spyOn(DiscussionContentView.prototype, "makeWmdEditor")
......@@ -15,8 +16,12 @@ describe "DiscussionThreadView", ->
spyOn(DiscussionUtil, "setWmdContent")
spyOn(ThreadResponseShowView.prototype, "convertMath")
afterEach ->
$.ajax.calls.reset()
jasmine.clock().uninstall()
renderWithContent = (view, content) ->
$.ajax.andCallFake((params) =>
$.ajax.and.callFake((params) =>
params.success(
createAjaxResponseJson(content, false),
'success'
......@@ -24,7 +29,7 @@ describe "DiscussionThreadView", ->
{always: ->}
)
view.render()
jasmine.Clock.tick(100)
jasmine.clock().tick(100)
renderWithTestResponses = (view, count, options) ->
renderWithContent(
......@@ -85,8 +90,8 @@ describe "DiscussionThreadView", ->
postResponse = (view, index) ->
testResponseJson = createTestResponseJson(index)
responseText = testResponseJson.body
spyOn(view, "getWmdContent").andReturn(responseText)
$.ajax.andCallFake((params) =>
spyOn(view, "getWmdContent").and.returnValue(responseText)
$.ajax.and.callFake((params) =>
expect(params.type).toEqual("POST")
expect(params.data.body).toEqual(responseText)
params.success(
......@@ -112,7 +117,7 @@ describe "DiscussionThreadView", ->
renderWithTestResponses(view, 1)
if mode == "inline"
view.expand()
spyOn(DiscussionUtil, "updateWithUndo").andCallFake(
spyOn(DiscussionUtil, "updateWithUndo").and.callFake(
(model, updates, safeAjaxParams, errorMsg) ->
model.set(updates)
)
......@@ -240,16 +245,18 @@ describe "DiscussionThreadView", ->
expect(@view.$el.find(".responses li").length).toEqual(0)
describe "focus", ->
it "sends focus to the conversation when opened", ->
it "sends focus to the conversation when opened", (done) ->
DiscussionViewSpecHelper.setNextResponseContent({resp_total: 0, children: []})
@view.render()
@view.expand()
waitsFor (->
self = @
jasmine.waitUntil(->
# This is the implementation of "toBeFocused". However, simply calling that method
# with no wait seems to be flaky.
article = @view.$el.find('.discussion-article')
article = self.view.$el.find('.discussion-article')
return article[0] == article[0].ownerDocument.activeElement
), "conversation did not receive focus", 3000
).then ->
done()
describe "expand/collapse", ->
it "shows/hides appropriate content", ->
......@@ -269,12 +276,12 @@ describe "DiscussionThreadView", ->
@view.render()
expect($(".post-body").text()).toEqual(expectedAbbreviation)
expect(DiscussionThreadShowView.prototype.convertMath).toHaveBeenCalled()
DiscussionThreadShowView.prototype.convertMath.reset()
DiscussionThreadShowView.prototype.convertMath.calls.reset()
@view.expand()
expect($(".post-body").text()).toEqual(longBody)
expect(DiscussionThreadShowView.prototype.convertMath).toHaveBeenCalled()
DiscussionThreadShowView.prototype.convertMath.reset()
DiscussionThreadShowView.prototype.convertMath.calls.reset()
@view.collapse()
expect($(".post-body").text()).toEqual(expectedAbbreviation)
......
......@@ -193,10 +193,11 @@ describe "DiscussionUserProfileView", ->
describe "pagination interaction", ->
beforeEach ->
@view = makeView(makeThreads(3), 1, 2)
spyOn($, "ajax")
deferred = $.Deferred();
spyOn($, "ajax").and.returnValue(deferred);
it "causes updated rendering", ->
$.ajax.andCallFake(
$.ajax.and.callFake(
(params) =>
params.success(
discussion_data: [{id: "on_page_42", body: "dummy body"}]
......@@ -211,7 +212,7 @@ describe "DiscussionUserProfileView", ->
it "handles AJAX errors", ->
spyOn(DiscussionUtil, "discussionAlert")
$.ajax.andCallFake(
$.ajax.and.callFake(
(params) =>
params.error()
{always: ->}
......
......@@ -50,7 +50,7 @@ class @DiscussionViewSpecHelper
triggerVoteEvent = (view, event, expectedUrl) ->
deferred = $.Deferred()
spyOn($, "ajax").andCallFake((params) =>
spyOn($, "ajax").and.callFake((params) =>
expect(params.url.toString()).toEqual(expectedUrl)
return deferred
)
......@@ -80,10 +80,10 @@ class @DiscussionViewSpecHelper
button.click()
expect(spy).toHaveBeenCalled()
spy.reset()
spy.calls.reset()
button.trigger($.Event("keydown", {which: 13}))
expect(spy).not.toHaveBeenCalled()
spy.reset()
spy.calls.reset()
button.trigger($.Event("keydown", {which: 32}))
expect(spy).toHaveBeenCalled()
......@@ -91,7 +91,7 @@ class @DiscussionViewSpecHelper
@checkButtonEvents(view, "toggleVote", ".action-vote")
@setNextResponseContent = (content) ->
$.ajax.andCallFake(
$.ajax.and.callFake(
(params) =>
params.success({"content": content})
{always: ->}
......
......@@ -4,7 +4,7 @@ describe "NewPostView", ->
DiscussionSpecHelper.setUpGlobals()
DiscussionSpecHelper.setUnderscoreFixtures()
window.$$course_id = "edX/999/test"
spyOn(DiscussionUtil, "makeWmdEditor").andCallFake(
spyOn(DiscussionUtil, "makeWmdEditor").and.callFake(
($content, $local, cls_identifier) ->
$local("." + cls_identifier).html("<textarea></textarea>")
)
......@@ -91,7 +91,7 @@ describe "NewPostView", ->
@view.$(".js-post-body textarea").val("dummy body")
@view.$(".forum-new-post-form").submit()
expect($.ajax).toHaveBeenCalled()
$.ajax.reset()
$.ajax.calls.reset()
)
describe "always cohort inline discussions ", ->
......@@ -209,7 +209,7 @@ describe "NewPostView", ->
it "posts to the correct URL", ->
topicId = "test_topic"
spyOn($, "ajax").andCallFake(
spyOn($, "ajax").and.callFake(
(params) ->
expect(params.url.path()).toEqual(DiscussionUtil.urlFor("create_thread", topicId))
{always: ->}
......
......@@ -25,14 +25,14 @@ describe 'ResponseCommentView', ->
spyOn(@view.$el, "remove")
setAjaxResult = (isSuccess) ->
spyOn($, "ajax").andCallFake(
spyOn($, "ajax").and.callFake(
(params) =>
(if isSuccess then params.success else params.error) {}
{always: ->}
)
it 'requires confirmation before deleting', ->
spyOn(window, "confirm").andReturn(false)
spyOn(window, "confirm").and.returnValue(false)
setAjaxResult(true)
@view._delete(@event)
expect(window.confirm).toHaveBeenCalled()
......@@ -50,7 +50,7 @@ describe 'ResponseCommentView', ->
@view._delete(@event)
expect(@event.preventDefault).toHaveBeenCalled()
expect($.ajax).toHaveBeenCalled()
expect($.ajax.mostRecentCall.args[0].url._parts.path).toEqual('/courses/edX/999/test/discussion/comments/01234567/delete')
expect($.ajax.calls.mostRecent().args[0].url._parts.path).toEqual('/courses/edX/999/test/discussion/comments/01234567/delete')
it 'handles ajax errors', ->
spyOn(DiscussionUtil, "discussionAlert")
......@@ -125,7 +125,7 @@ describe 'ResponseCommentView', ->
@view.$el.find(".edit-comment-body").html($("<textarea></textarea>"))
@view.$el.find(".edit-comment-body textarea").val(@updatedBody)
spyOn(@view, 'cancelEdit')
spyOn($, "ajax").andCallFake(
spyOn($, "ajax").and.callFake(
(params) =>
if @ajaxSucceed
params.success()
......@@ -138,8 +138,8 @@ describe 'ResponseCommentView', ->
@ajaxSucceed = true
@view.update(DiscussionSpecHelper.makeEventSpy())
expect($.ajax).toHaveBeenCalled()
expect($.ajax.mostRecentCall.args[0].url._parts.path).toEqual('/courses/edX/999/test/discussion/comments/01234567/update')
expect($.ajax.mostRecentCall.args[0].data.body).toEqual(@updatedBody)
expect($.ajax.calls.mostRecent().args[0].url._parts.path).toEqual('/courses/edX/999/test/discussion/comments/01234567/update')
expect($.ajax.calls.mostRecent().args[0].data.body).toEqual(@updatedBody)
expect(@view.model.get("body")).toEqual(@updatedBody)
expect(@view.cancelEdit).toHaveBeenCalled()
......@@ -148,8 +148,8 @@ describe 'ResponseCommentView', ->
@ajaxSucceed = false
@view.update(DiscussionSpecHelper.makeEventSpy())
expect($.ajax).toHaveBeenCalled()
expect($.ajax.mostRecentCall.args[0].url._parts.path).toEqual('/courses/edX/999/test/discussion/comments/01234567/update')
expect($.ajax.mostRecentCall.args[0].data.body).toEqual(@updatedBody)
expect($.ajax.calls.mostRecent().args[0].url._parts.path).toEqual('/courses/edX/999/test/discussion/comments/01234567/update')
expect($.ajax.calls.mostRecent().args[0].data.body).toEqual(@updatedBody)
expect(@view.model.get("body")).toEqual(originalBody)
expect(@view.cancelEdit).not.toHaveBeenCalled()
expect(@view.$(".edit-comment-form-errors *").length).toEqual(1)
......@@ -108,6 +108,7 @@ describe "ThreadResponseShowView", ->
expect(@view.$(".posted-details").text()).not.toMatch("\sby\s")
it "re-renders correctly when endorsement changes", ->
spyOn($, "ajax").and.returnValue($.Deferred())
DiscussionUtil.loadRoles({"Moderator": [parseInt(window.user.id)]})
@thread.set("thread_type", "question")
@view.render()
......@@ -118,6 +119,7 @@ describe "ThreadResponseShowView", ->
expect(@view.$(".posted-details").text()).not.toMatch("marked as answer")
it "allows a moderator to mark an answer in a question thread", ->
spyOn($, "ajax").and.returnValue($.Deferred())
DiscussionUtil.loadRoles({"Moderator": [parseInt(window.user.id)]})
@thread.set({
"thread_type": "question",
......@@ -131,6 +133,7 @@ describe "ThreadResponseShowView", ->
expect(endorseButton).toHaveClass("is-checked")
it "allows the author of a question thread to mark an answer", ->
spyOn($, "ajax").and.returnValue($.Deferred())
@thread.set({
"thread_type": "question",
"user_id": window.user.id
......@@ -199,7 +202,7 @@ describe "ThreadResponseShowView", ->
"username": "test_endorser",
"time": new Date().toISOString()
})
spyOn(DiscussionUtil, 'urlFor').andReturn('test_endorser_url')
spyOn(DiscussionUtil, 'urlFor').and.returnValue('test_endorser_url')
checkUserLink = (element, is_ta, is_staff) ->
expect(element.find('a.username').length).toEqual(1)
......@@ -217,11 +220,11 @@ describe "ThreadResponseShowView", ->
checkUserLink($el, false, false)
it "renders correctly for a community TA-endorsed response", ->
spyOn(DiscussionUtil, 'isTA').andReturn(true)
spyOn(DiscussionUtil, 'isTA').and.returnValue(true)
$el = $('#fixture-element').html(@view.getEndorserDisplay())
checkUserLink($el, true, false)
it "renders correctly for a staff-endorsed response", ->
spyOn(DiscussionUtil, 'isStaff').andReturn(true)
spyOn(DiscussionUtil, 'isStaff').and.returnValue(true)
$el = $('#fixture-element').html(@view.getEndorserDisplay())
checkUserLink($el, false, true)
......@@ -28,14 +28,14 @@ describe "XBlock", ->
window.TestRuntime = {}
@runtimeA = {name: 'runtimeA'}
@runtimeZ = {name: 'runtimeZ'}
TestRuntime.vA = jasmine.createSpy().andReturn(@runtimeA)
TestRuntime.vZ = jasmine.createSpy().andReturn(@runtimeZ)
TestRuntime.vA = jasmine.createSpy().and.returnValue(@runtimeA)
TestRuntime.vZ = jasmine.createSpy().and.returnValue(@runtimeZ)
window.initFnA = jasmine.createSpy()
window.initFnZ = jasmine.createSpy()
@fakeChildren = ['list', 'of', 'children']
spyOn(XBlock, 'initializeXBlocks').andReturn(@fakeChildren)
spyOn(XBlock, 'initializeXBlocks').and.returnValue(@fakeChildren)
@vANode = $('#vA')[0]
@vZNode = $('#vZ')[0]
......@@ -54,11 +54,11 @@ describe "XBlock", ->
expect(window.initFnZ).toHaveBeenCalledWith(@runtimeZ, @vZNode, {})
it "loads when missing versions", ->
expect(@missingVersionBlock.element).toBe($('#missing-version'))
expect(@missingVersionBlock.element).toBe($('#missing-version')[0])
expect(@missingVersionBlock.name).toBe('no-version')
it "loads when missing init fn", ->
expect(@missingInitBlock.element).toBe($('#missing-init'))
expect(@missingInitBlock.element).toBe($('#missing-init')[0])
expect(@missingInitBlock.name).toBe('no-init')
it "adds names to blocks", ->
......
// Generated by CoffeeScript 1.6.1
(function() {
define(["jquery", "common/js/components/views/feedback", "common/js/components/views/feedback_notification", "common/js/components/views/feedback_alert", "common/js/components/views/feedback_prompt", 'common/js/spec_helpers/view_helpers', "sinon", "jquery.simulate"],
'use strict';
define(["jquery", "common/js/components/views/feedback", "common/js/components/views/feedback_notification",
"common/js/components/views/feedback_alert", "common/js/components/views/feedback_prompt",
'common/js/spec_helpers/view_helpers', "sinon", "jquery.simulate", "jasmine-waituntil"],
function($, SystemFeedback, NotificationView, AlertView, PromptView, ViewHelpers, sinon) {
var tpl;
tpl = readFixtures('system-feedback.underscore');
tpl = readFixtures('common/templates/components/system-feedback.underscore');
var isFocused = function(actual) {
return $(actual)[0] === $(actual)[0].ownerDocument.activeElement;
};
beforeEach(function() {
setFixtures(sandbox({
id: "page-alert"
......@@ -19,30 +26,24 @@
id: "system-feedback-tpl",
type: "text/template"
}).text(tpl));
return this.addMatchers({
return jasmine.addMatchers({
toBeShown: function() {
return this.actual.hasClass("is-shown") && !this.actual.hasClass("is-hiding");
return {
compare: function (actual) {
return {
pass: actual.hasClass("is-shown") && !actual.hasClass("is-hiding")
};
}
};
},
toBeHiding: function() {
return this.actual.hasClass("is-hiding") && !this.actual.hasClass("is-shown");
},
toContainText: function(text) {
var trimmedText;
trimmedText = $.trim(this.actual.text());
if (text && $.isFunction(text.test)) {
return text.test(trimmedText);
} else {
return trimmedText.indexOf(text) !== -1;
}
},
toHaveBeenPrevented: function() {
var eventName, selector;
eventName = this.actual.eventName;
selector = this.actual.selector;
this.message = function() {
return ["Expected event " + eventName + " to have been prevented on " + selector, "Expected event " + eventName + " not to have been prevented on " + selector];
return {
compare: function (actual) {
return {
pass: actual.hasClass("is-hiding") && !actual.hasClass("is-shown")
};
}
};
return jasmine.JQuery.events.wasPrevented(selector, eventName);
}
});
});
......@@ -52,9 +53,9 @@
title: "Portal",
message: "Welcome to the Aperture Science Computer-Aided Enrichment Center"
};
this.renderSpy = spyOn(AlertView.Confirmation.prototype, 'render').andCallThrough();
this.showSpy = spyOn(AlertView.Confirmation.prototype, 'show').andCallThrough();
this.hideSpy = spyOn(AlertView.Confirmation.prototype, 'hide').andCallThrough();
this.renderSpy = spyOn(AlertView.Confirmation.prototype, 'render').and.callThrough();
this.showSpy = spyOn(AlertView.Confirmation.prototype, 'show').and.callThrough();
this.hideSpy = spyOn(AlertView.Confirmation.prototype, 'hide').and.callThrough();
return this.clock = sinon.useFakeTimers();
});
afterEach(function() {
......@@ -122,30 +123,35 @@
actions: {
primary: {
text: "Yes, I'm sure.",
"class": "confirm-button",
"class": "confirm-button"
},
secondary: {
text: "Cancel",
"class": "cancel-button",
"class": "cancel-button"
}
}
}
this.inFocusSpy = spyOn(PromptView.Confirmation.prototype, 'inFocus').andCallThrough();
return this.outFocusSpy = spyOn(PromptView.Confirmation.prototype, 'outFocus').andCallThrough();
};
this.inFocusSpy = spyOn(PromptView.Confirmation.prototype, 'inFocus').and.callThrough();
this.outFocusSpy = spyOn(PromptView.Confirmation.prototype, 'outFocus').and.callThrough();
});
it("is focused on show", function() {
it("is focused on show", function(done) {
var view;
view = new PromptView.Confirmation(this.options).show();
expect(this.inFocusSpy).toHaveBeenCalled();
return ViewHelpers.verifyElementInFocus(view, ".wrapper-prompt")
jasmine.waitUntil(function () {
return isFocused(view.$(".wrapper-prompt"));
}).always(done);
});
it("is not focused on hide", function() {
it("is not focused on hide", function(done) {
var view;
view = new PromptView.Confirmation(this.options).hide();
expect(this.outFocusSpy).toHaveBeenCalled();
return ViewHelpers.verifyElementNotInFocus(view, ".wrapper-prompt")
jasmine.waitUntil(function () {
return !isFocused(view.$(".wrapper-prompt"));
}).always(done);
});
it("traps keyboard focus when moving forward", function() {
it("traps keyboard focus when moving forward", function(done) {
var view;
view = new PromptView.Confirmation(this.options).show();
expect(this.inFocusSpy).toHaveBeenCalled();
......@@ -153,9 +159,12 @@
"keydown",
{ keyCode: $.simulate.keyCode.TAB }
);
return ViewHelpers.verifyElementInFocus(view, ".action-primary")
jasmine.waitUntil(function () {
return isFocused(view.$(".action-primary"));
}).always(done);
});
it("traps keyboard focus when moving backward", function() {
it("traps keyboard focus when moving backward", function(done) {
var view;
view = new PromptView.Confirmation(this.options).show();
expect(this.inFocusSpy).toHaveBeenCalled();
......@@ -163,7 +172,9 @@
"keydown",
{ keyCode: $.simulate.keyCode.TAB, shiftKey: true }
);
return ViewHelpers.verifyElementInFocus(view, ".action-secondary")
jasmine.waitUntil(function () {
return isFocused(view.$(".action-secondary"));
}).always(done);
});
return it("changes class on body", function() {
var view;
......@@ -175,14 +186,15 @@
});
});
describe("NotificationView.Mini", function() {
var view;
beforeEach(function() {
return this.view = new NotificationView.Mini();
view = new NotificationView.Mini();
});
it("should have minShown set to 1250 by default", function() {
return expect(this.view.options.minShown).toEqual(1250);
return expect(view.options.minShown).toEqual(1250);
});
return it("should have closeIcon set to false by default", function() {
return expect(this.view.options.closeIcon).toBeFalsy();
return expect(view.options.closeIcon).toBeFalsy();
});
});
xdescribe("SystemFeedback click events", function() {
......@@ -301,9 +313,9 @@
return describe("NotificationView minShown and maxShown", function() {
beforeEach(function() {
this.showSpy = spyOn(NotificationView.Confirmation.prototype, 'show');
this.showSpy.andCallThrough();
this.showSpy.and.callThrough();
this.hideSpy = spyOn(NotificationView.Confirmation.prototype, 'hide');
this.hideSpy.andCallThrough();
this.hideSpy.and.callThrough();
return this.clock = sinon.useFakeTimers();
});
afterEach(function() {
......
......@@ -36,7 +36,9 @@
'edxicons': 'edx-pattern-library/js/edx-icons',
'draggabilly': 'js/vendor/draggabilly',
'jasmine-stealth': 'js/libs/jasmine-stealth',
'jasmine-waituntil': 'js/libs/jasmine-waituntil'
'jasmine-waituntil': 'js/libs/jasmine-waituntil',
'jasmine-extensions': 'js/libs/jasmine-extensions',
'URI': 'js/vendor/URI.min'
},
shim: {
'gettext': {
......@@ -145,6 +147,9 @@
'jasmine-waituntil': {
deps: ['jquery']
},
'jasmine-extensions': {
deps: ['jquery']
},
"sinon": {
exports: "sinon"
},
......
......@@ -28,10 +28,12 @@ define(['sinon', 'underscore', 'URI'], function(sinon, _, URI) {
* Get a reference to the mocked server, and respond
* to all requests with the specified statusCode.
*/
fakeServer = function (that, response) {
fakeServer = function (response) {
var server = sinon.fakeServer.create();
that.after(function() {
server.restore();
afterEach(function() {
if (server) {
server.restore();
}
});
server.respondWith(response);
return server;
......@@ -42,16 +44,19 @@ define(['sinon', 'underscore', 'URI'], function(sinon, _, URI) {
* return a reference to the Array. This allows tests
* to respond for individual requests.
*/
fakeRequests = function (that) {
fakeRequests = function () {
var requests = [],
xhr = sinon.useFakeXMLHttpRequest();
xhr = sinon.useFakeXMLHttpRequest();
requests.currentIndex = 0;
xhr.onCreate = function(request) {
requests.push(request);
};
that.after(function() {
xhr.restore();
afterEach(function() {
if (xhr && xhr.hasOwnProperty('restore')) {
xhr.restore();
}
});
return requests;
};
......@@ -88,11 +93,12 @@ define(['sinon', 'underscore', 'URI'], function(sinon, _, URI) {
};
expectJsonRequest = function(requests, method, url, jsonRequest) {
jsonRequest = jsonRequest || null;
var request = currentRequest(requests);
expect(request.readyState).toEqual(XML_HTTP_READY_STATES.OPENED);
expect(request.url).toEqual(url);
expect(request.method).toEqual(method);
expect(JSON.parse(request.requestBody)).toEqual(jsonRequest);
expect(JSON.parse(request.requestBody)).toEqual(jsonRequest === undefined ? null : jsonRequest);
};
/**
......
......@@ -32,12 +32,12 @@ define(["backbone"],
};
// Stub out the Backbone router so that the browser doesn't actually navigate
spyOn(Backbone.history, '_updateHash').andCallFake(function (location, fragment, replace) {
spyOn(Backbone.history, '_updateHash').and.callFake(function (location, fragment) {
history.currentFragment = fragment;
});
// Stub out getHash so that Backbone thinks that the browser has navigated
spyOn(Backbone.history, 'getHash').andCallFake(function () {
spyOn(Backbone.history, 'getHash').and.callFake(function () {
return history.currentFragment;
});
};
......
......@@ -10,16 +10,18 @@ define(["jquery", "common/js/components/views/feedback_notification", "common/js
verifyFeedbackHidden, createNotificationSpy, verifyNotificationShowing,
verifyNotificationHidden, createPromptSpy, confirmPrompt, inlineEdit, verifyInlineEditChange,
installMockAnalytics, removeMockAnalytics, verifyPromptShowing, verifyPromptHidden,
clickDeleteItem, patchAndVerifyRequest, submitAndVerifyFormSuccess, submitAndVerifyFormError,
verifyElementInFocus, verifyElementNotInFocus;
clickDeleteItem, patchAndVerifyRequest, submitAndVerifyFormSuccess, submitAndVerifyFormError;
installViewTemplates = function() {
appendSetFixtures('<div id="page-notification"></div>');
};
createFeedbackSpy = function(type, intent) {
var feedbackSpy = spyOnConstructor(type, intent, ['show', 'hide']);
feedbackSpy.show.andReturn(feedbackSpy);
var feedbackSpy = jasmine.stealth.spyOnConstructor(type, intent, ['show', 'hide']);
feedbackSpy.show.and.returnValue(feedbackSpy);
if (afterEach) {
afterEach(jasmine.stealth.clearSpies);
}
return feedbackSpy;
};
......@@ -28,7 +30,7 @@ define(["jquery", "common/js/components/views/feedback_notification", "common/js
expect(feedbackSpy.constructor).toHaveBeenCalled();
expect(feedbackSpy.show).toHaveBeenCalled();
expect(feedbackSpy.hide).not.toHaveBeenCalled();
options = feedbackSpy.constructor.mostRecentCall.args[0];
options = feedbackSpy.constructor.calls.mostRecent().args[0];
expect(options.title).toMatch(text);
};
......@@ -55,9 +57,9 @@ define(["jquery", "common/js/components/views/feedback_notification", "common/js
confirmPrompt = function(promptSpy, pressSecondaryButton) {
expect(promptSpy.constructor).toHaveBeenCalled();
if (pressSecondaryButton) {
promptSpy.constructor.mostRecentCall.args[0].actions.secondary.click(promptSpy);
promptSpy.constructor.calls.mostRecent().args[0].actions.secondary.click(promptSpy);
} else {
promptSpy.constructor.mostRecentCall.args[0].actions.primary.click(promptSpy);
promptSpy.constructor.calls.mostRecent().args[0].actions.primary.click(promptSpy);
}
};
......@@ -128,22 +130,6 @@ define(["jquery", "common/js/components/views/feedback_notification", "common/js
verifyNotificationShowing(notificationSpy, /Saving/);
};
verifyElementInFocus = function(view, selector) {
waitsFor(
function() { return view.$(selector + ':focus').length === 1; },
"element to have focus: " + selector,
500
);
};
verifyElementNotInFocus = function(view, selector) {
waitsFor(
function() { return view.$(selector + ':focus').length === 0; },
"element to not have focus: " + selector,
500
);
};
return {
'installViewTemplates': installViewTemplates,
'createNotificationSpy': createNotificationSpy,
......@@ -160,9 +146,7 @@ define(["jquery", "common/js/components/views/feedback_notification", "common/js
'clickDeleteItem': clickDeleteItem,
'patchAndVerifyRequest': patchAndVerifyRequest,
'submitAndVerifyFormSuccess': submitAndVerifyFormSuccess,
'submitAndVerifyFormError': submitAndVerifyFormError,
'verifyElementInFocus': verifyElementInFocus,
'verifyElementNotInFocus': verifyElementNotInFocus
'submitAndVerifyFormError': submitAndVerifyFormError
};
});
}).call(this, define || RequireJS.define);
// Extensions to Jasmine.
//
// This file adds the following:
// 1. Custom matchers that may be helpful project-wise.
// 2. Copies of some matchers from Jasmine-jQuery.
// Because Jasmine-Jquery uses its own version of JQuery, events registered in the code
// using the platform version of JQuery are not "noticed" by Jasmine-jQuery matchers.
// Similarly equality matching does not work either. So after the platform version of
// jQuery has been loaded, we set these matchers up again in this module.
(function(root, factory) {
/* jshint strict: false */
factory(root, root.jQuery);
}((function() {
/* jshint strict: false */
return this;
}()), function(window, $) {
'use strict';
// Add custom Jasmine matchers.
beforeEach(function() {
jasmine.addMatchers(window.imagediff.jasmine);
jasmine.addMatchers({
toHaveAttrs: function() {
return {
compare: function(actual, attrs) {
var result = {},
element = actual;
if ($.isEmptyObject(attrs)) {
return {
pass: false
};
}
result.pass = _.every(attrs, function(value, name) {
return element.attr(name) === value;
});
return result;
}
};
},
toBeInRange: function() {
return {
compare: function(actual, min, max) {
return {
pass: min <= actual && actual <= max
};
}
};
},
toBeInArray: function() {
return {
compare: function(actual, array) {
return {
pass: $.inArray(actual, array) > -1
};
}
};
}
});
});
/* jshint ignore:start */
// All the code below is taken from:
// https://github.com/velesin/jasmine-jquery/blob/2.1.1/lib/jasmine-jquery.js
beforeEach(function() {
jasmine.addMatchers({
toHandle: function() {
return {
compare: function(actual, event) {
if (!actual || actual.length === 0) return {
pass: false
};
var events = $._data($(actual).get(0), "events");
if (!events || !event || typeof event !== "string") {
return {
pass: false
};
}
var namespaces = event.split("."),
eventType = namespaces.shift(),
sortedNamespaces = namespaces.slice(0).sort(),
namespaceRegExp = new RegExp("(^|\\.)" + sortedNamespaces.join("\\.(?:.*\\.)?") + "(\\.|$)");
if (events[eventType] && namespaces.length) {
for (var i = 0; i < events[eventType].length; i++) {
var namespace = events[eventType][i].namespace;
if (namespaceRegExp.test(namespace))
return {
pass: true
};
}
} else {
return {
pass: (events[eventType] && events[eventType].length > 0)
};
}
return {
pass: false
};
}
};
},
toHandleWith: function() {
return {
compare: function(actual, eventName, eventHandler) {
if (!actual || actual.length === 0) return {
pass: false
};
var normalizedEventName = eventName.split('.')[0],
stack = $._data($(actual).get(0), "events")[normalizedEventName];
for (var i = 0; i < stack.length; i++) {
if (stack[i].handler == eventHandler) return {
pass: true
};
}
return {
pass: false
};
}
};
}
});
jasmine.addCustomEqualityTester(function(a, b) {
if (a && b) {
if (a instanceof $ || jasmine.isDomNode(a)) {
var $a = $(a);
if (b instanceof $)
return $a.length == b.length && a.is(b);
return $a.is(b);
}
if (b instanceof $ || jasmine.isDomNode(b)) {
var $b = $(b);
if (a instanceof $)
return a.length == $b.length && $b.is(a);
return $(b).is(a);
}
}
});
jasmine.addCustomEqualityTester(function(a, b) {
if (a instanceof $ && b instanceof $ && a.size() == b.size())
return a.is(b);
});
});
var data = {
spiedEvents: {},
handlers: []
};
jasmine.jQuery.events = {
spyOn: function(selector, eventName) {
var handler = function(e) {
var calls = (typeof data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)] !== 'undefined') ? data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)].calls : 0;
data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)] = {
args: jasmine.util.argsToArray(arguments),
calls: ++calls
};
};
$(selector).on(eventName, handler);
data.handlers.push(handler);
return {
selector: selector,
eventName: eventName,
handler: handler,
reset: function() {
delete data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)];
},
calls: {
count: function() {
return data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)] ?
data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)].calls : 0;
},
any: function() {
return data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)] ?
!!data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)].calls : false;
}
}
};
},
args: function(selector, eventName) {
var actualArgs = data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)].args;
if (!actualArgs) {
throw "There is no spy for " + eventName + " on " + selector.toString() + ". Make sure to create a spy using spyOnEvent.";
}
return actualArgs;
},
wasTriggered: function(selector, eventName) {
return !!(data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)]);
},
wasTriggeredWith: function(selector, eventName, expectedArgs, util, customEqualityTesters) {
var actualArgs = jasmine.jQuery.events.args(selector, eventName).slice(1);
if (Object.prototype.toString.call(expectedArgs) !== '[object Array]')
actualArgs = actualArgs[0];
return util.equals(actualArgs, expectedArgs, customEqualityTesters);
},
wasPrevented: function(selector, eventName) {
var spiedEvent = data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)],
args = (jasmine.util.isUndefined(spiedEvent)) ? {} : spiedEvent.args,
e = args ? args[0] : undefined;
return e && e.isDefaultPrevented();
},
wasStopped: function(selector, eventName) {
var spiedEvent = data.spiedEvents[jasmine.spiedEventsKey(selector, eventName)],
args = (jasmine.util.isUndefined(spiedEvent)) ? {} : spiedEvent.args,
e = args ? args[0] : undefined;
return e && e.isPropagationStopped();
},
cleanUp: function() {
data.spiedEvents = {};
data.handlers = [];
}
};
/* jshint ignore:end */
}));
// Custom library to replace the legacy non jasmine 2.0 compatible jasmine-stealth
// jshint ignore: start
(function (root, factory) {
factory(root, root.jasmine, root._);
}((function () {
return this;
}()), function (window, jasmine, _) {
var fake, clearSpies, spyOnConstructor, unfakes = [];
clearSpies = function () {
_.each(unfakes, function (u) {
return u();
});
return unfakes = [];
};
fake = function (owner, thingToFake, newThing) {
var originalThing;
originalThing = owner[thingToFake];
owner[thingToFake] = newThing;
return unfakes.push(function () {
return owner[thingToFake] = originalThing;
});
};
spyOnConstructor = function (owner, classToFake, methodsToSpy) {
var fakeClass, spies;
fakeClass = (function () {
function _Class() {
spies.constructor.apply(this, arguments);
}
return _Class;
})();
if (!methodsToSpy) {
methodsToSpy = [];
}
if (_.isString(methodsToSpy)) {
methodsToSpy = [methodsToSpy];
}
spies = {
constructor: jasmine.createSpy('' + classToFake + '\'s constructor')
};
_.each(methodsToSpy, function (methodName) {
spies[methodName] = jasmine.createSpy('' + classToFake + '#' + methodName);
return fakeClass.prototype[methodName] = function () {
return spies[methodName].apply(this, arguments);
};
});
fake(owner, classToFake, fakeClass);
return spies;
};
jasmine.stealth = {
spyOnConstructor: spyOnConstructor,
clearSpies: clearSpies
};
}));
\ No newline at end of file
// Takes a latch function and optionally timeout and error message.
// Polls the latch function until the it returns true or the maximum timeout expires
// whichever comes first.
(function(root, factory) {
/* jshint strict: false */
factory(root, root.jQuery);
}((function() {
/* jshint strict: false */
return this;
}()), function(window, $) {
'use strict';
var MAX_TIMEOUT = jasmine.DEFAULT_TIMEOUT_INTERVAL;
var realSetTimeout = setTimeout;
var realClearTimeout = clearTimeout;
jasmine.waitUntil = function(conditionalFn, maxTimeout, message) {
var deferred = $.Deferred(),
elapsedTimeInMs = 0,
timeout;
maxTimeout = maxTimeout || MAX_TIMEOUT;
message = message || 'Timeout has expired';
var fn = function() {
elapsedTimeInMs += 50;
if (conditionalFn()) {
if (timeout) { realClearTimeout(timeout); }
deferred.resolve();
} else {
if (elapsedTimeInMs >= maxTimeout) {
// explicitly fail the spec with the given message
fail(message); // jshint ignore:line
// clear timeout and reject the promise
realClearTimeout(timeout);
deferred.reject();
return;
}
timeout = realSetTimeout(fn, 50);
}
};
realSetTimeout(fn, 50);
return deferred.promise();
};
}));
describe("CSS3 workarounds", function() {
'use strict';
var pointerEventsNone = window.pointerEventsNone;
describe("pointer-events", function() {
beforeEach(function() {
var html = "<a href='#' class='is-disabled'>What wondrous life in this I lead</a>";
......@@ -21,17 +23,7 @@ describe("CSS3 workarounds", function() {
});
it("should prevent default when pointerEvents is not Supported", function() {
// mock document.body.style so it does not include 'pointerEvents'
var mockBodyStyle = {},
bodyStyleKeys = Object.keys(document.body.style);
for (var index = 0; index < bodyStyleKeys.length; index++) {
var key = bodyStyleKeys[index];
if (key !== "pointerEvents") {
mockBodyStyle[key] = document.body.style[key];
};
};
pointerEventsNone(".is-disabled", mockBodyStyle);
pointerEventsNone(".is-disabled", {});
spyOnEvent(".is-disabled", "click");
$(".is-disabled").click();
expect("click").toHaveBeenPreventedOn(".is-disabled");
......
......@@ -19,34 +19,34 @@
});
it("should make an AJAX request to the correct URL", function () {
spyOn($, 'ajax').andReturn(deferred);
spyOn($, 'ajax').and.returnValue(deferred);
Language.init();
lang_selector.trigger('change');
expect($.ajax.mostRecentCall.args[0].url).toEqual("/api/user/v1/preferences/test1/");
expect($.ajax.calls.mostRecent().args[0].url).toEqual("/api/user/v1/preferences/test1/");
});
it("should make an AJAX request with correct type", function () {
spyOn($, 'ajax').andReturn(deferred);
spyOn($, 'ajax').and.returnValue(deferred);
Language.init();
lang_selector.trigger('change');
expect($.ajax.mostRecentCall.args[0].type).toEqual("PATCH");
expect($.ajax.calls.mostRecent().args[0].type).toEqual("PATCH");
});
it("should make an AJAX request with correct data", function () {
spyOn($, 'ajax').andReturn(deferred);
spyOn($, 'ajax').and.returnValue(deferred);
Language.init();
lang_selector.val('ar');
lang_selector.trigger('change');
expect($.ajax.mostRecentCall.args[0].data).toEqual('{"pref-lang":"ar"}');
expect($.ajax.calls.mostRecent().args[0].data).toEqual('{"pref-lang":"ar"}');
// change to 'en' from 'ar'
lang_selector.val('en');
lang_selector.trigger('change');
expect($.ajax.mostRecentCall.args[0].data).toEqual('{"pref-lang":"en"}');
expect($.ajax.calls.mostRecent().args[0].data).toEqual('{"pref-lang":"en"}');
});
it("should call refresh on ajax failure", function () {
spyOn($, 'ajax').andCallFake(function () {
spyOn($, 'ajax').and.callFake(function () {
var d = $.Deferred();
d.reject();
return d.promise();
......
......@@ -11,24 +11,37 @@ describe('TooltipManager', function () {
this.element = $('#test-id');
this.tooltip = new TooltipManager(document.body);
jasmine.Clock.useMock();
jasmine.clock().install();
// Set default dimensions to make testing easer.
$('.tooltip').height(HEIGHT).width(WIDTH);
// Re-write default jasmine-jquery to consider opacity.
this.addMatchers({
jasmine.addMatchers({
toBeVisible: function() {
return this.actual.is(':visible') || parseFloat(this.actual.css('opacity'));
return {
compare: function (actual) {
return {
pass: actual.is(':visible') || parseFloat(actual.css('opacity'))
};
}
};
},
toBeHidden: function() {
return this.actual.is(':hidden') || !parseFloat(this.actual.css('opacity'));
},
toBeHidden: function () {
return {
compare: function (actual) {
return {
pass: actual.is(':hidden') || !parseFloat(actual.css('opacity'))
};
}
};
}
});
});
afterEach(function () {
this.tooltip.destroy();
jasmine.clock().uninstall();
});
showTooltip = function (element) {
......@@ -36,7 +49,7 @@ describe('TooltipManager', function () {
pageX: PAGE_X,
pageY: PAGE_Y
}));
jasmine.Clock.tick(500);
jasmine.clock().tick(500);
};
it('can destroy itself', function () {
......@@ -58,7 +71,7 @@ describe('TooltipManager', function () {
showTooltip(this.element);
expect($('.tooltip')).toBeVisible();
this.element.trigger($.Event("mouseout"));
jasmine.Clock.tick(50);
jasmine.clock().tick(50);
expect($('.tooltip')).toBeHidden();
});
......@@ -66,7 +79,7 @@ describe('TooltipManager', function () {
showTooltip(this.element);
expect($('.tooltip')).toBeVisible();
this.element.trigger($.Event("click"));
jasmine.Clock.tick(50);
jasmine.clock().tick(50);
expect($('.tooltip')).toBeHidden();
});
......
......@@ -2,7 +2,7 @@
// supported in older browsers
var pointerEventsNone = function (selector, supportedStyles) {
// Check to see if the brower supports 'pointer-events' css rule.
// Check to see if the browser supports 'pointer-events' css rule.
// If it doesn't, use javascript to stop the link from working
// when clicked.
$(selector).click(function (event) {
......
......@@ -268,52 +268,71 @@
return element;
}
function imageDiffEqualMessage (actual, expected) {
return function () {
var
div = get('div'),
a = get('div', '<div>Actual:</div>'),
b = get('div', '<div>Expected:</div>'),
c = get('div', '<div>Diff:</div>'),
diff = imagediff.diff(actual, expected),
canvas = getCanvas(),
context;
canvas.height = diff.height;
canvas.width = diff.width;
div.style.overflow = 'hidden';
a.style.float = 'left';
b.style.float = 'left';
c.style.float = 'left';
context = canvas.getContext('2d');
context.putImageData(diff, 0, 0);
a.appendChild(toCanvas(actual));
b.appendChild(toCanvas(expected));
c.appendChild(canvas);
div.appendChild(a);
div.appendChild(b);
div.appendChild(c);
return div;
};
}
jasmine = {
toBeImageData : function () {
return imagediff.isImageData(this.actual);
return {
compare: function () {
return {
pass: imagediff.isImageData(this.actual)
}
}
};
},
toImageDiffEqual : function (expected, tolerance) {
if (typeof (document) !== UNDEFINED) {
this.message = function () {
toImageDiffEqual: function () {
return {
compare: function (actual, expected, tolerance) {
var
div = get('div'),
a = get('div', '<div>Actual:</div>'),
b = get('div', '<div>Expected:</div>'),
c = get('div', '<div>Diff:</div>'),
diff = imagediff.diff(this.actual, expected),
canvas = getCanvas(),
context;
canvas.height = diff.height;
canvas.width = diff.width;
div.style.overflow = 'hidden';
a.style.float = 'left';
b.style.float = 'left';
c.style.float = 'left';
context = canvas.getContext('2d');
context.putImageData(diff, 0, 0);
a.appendChild(toCanvas(this.actual));
b.appendChild(toCanvas(expected));
c.appendChild(canvas);
div.appendChild(a);
div.appendChild(b);
div.appendChild(c);
return [
div,
"Expected not to be equal."
];
};
}
return imagediff.equal(this.actual, expected, tolerance);
result = {};
result.pass = imagediff.equal(actual, expected, tolerance);
if (typeof (document) !== UNDEFINED) {
result.message = imageDiffEqualMessage(actual, expected);
}
return result;
},
negativeCompare: function (actual, expected, tolerance) {
return {
pass: !imagediff.equal(actual, expected, tolerance),
message: 'Expected not to be equal.'
};
}
};
}
};
......
// Generated by CoffeeScript 1.3.3
/*
jasmine-stealth 0.0.12
Makes Jasmine spies a bit more robust
site: https://github.com/searls/jasmine-stealth
*/
(function() {
var Captor, fake, root, unfakes, whatToDoWhenTheSpyGetsCalled, _,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
root = this;
_ = function(obj) {
return {
each: function(iterator) {
var item, _i, _len, _results;
_results = [];
for (_i = 0, _len = obj.length; _i < _len; _i++) {
item = obj[_i];
_results.push(iterator(item));
}
return _results;
},
isFunction: function() {
return Object.prototype.toString.call(obj) === "[object Function]";
},
isString: function() {
return Object.prototype.toString.call(obj) === "[object String]";
}
};
};
root.spyOnConstructor = function(owner, classToFake, methodsToSpy) {
var fakeClass, spies;
if (methodsToSpy == null) {
methodsToSpy = [];
}
if (_(methodsToSpy).isString()) {
methodsToSpy = [methodsToSpy];
}
spies = {
constructor: jasmine.createSpy("" + classToFake + "'s constructor")
};
fakeClass = (function() {
function _Class() {
spies.constructor.apply(this, arguments);
}
return _Class;
})();
_(methodsToSpy).each(function(methodName) {
spies[methodName] = jasmine.createSpy("" + classToFake + "#" + methodName);
return fakeClass.prototype[methodName] = function() {
return spies[methodName].apply(this, arguments);
};
});
fake(owner, classToFake, fakeClass);
return spies;
};
unfakes = [];
afterEach(function() {
_(unfakes).each(function(u) {
return u();
});
return unfakes = [];
});
fake = function(owner, thingToFake, newThing) {
var originalThing;
originalThing = owner[thingToFake];
owner[thingToFake] = newThing;
return unfakes.push(function() {
return owner[thingToFake] = originalThing;
});
};
root.stubFor = root.spyOn;
jasmine.createStub = jasmine.createSpy;
jasmine.createStubObj = function(baseName, stubbings) {
var name, obj, stubbing;
if (stubbings.constructor === Array) {
return jasmine.createSpyObj(baseName, stubbings);
} else {
obj = {};
for (name in stubbings) {
stubbing = stubbings[name];
obj[name] = jasmine.createSpy(baseName + "." + name);
if (_(stubbing).isFunction()) {
obj[name].andCallFake(stubbing);
} else {
obj[name].andReturn(stubbing);
}
}
return obj;
}
};
whatToDoWhenTheSpyGetsCalled = function(spy) {
var matchesStub, priorStubbing;
matchesStub = function(stubbing, args, context) {
switch (stubbing.type) {
case "args":
return jasmine.getEnv().equals_(stubbing.ifThis, jasmine.util.argsToArray(args));
case "context":
return jasmine.getEnv().equals_(stubbing.ifThis, context);
}
};
priorStubbing = spy.plan();
return spy.andCallFake(function() {
var i, stubbing;
i = 0;
while (i < spy._stealth_stubbings.length) {
stubbing = spy._stealth_stubbings[i];
if (matchesStub(stubbing, arguments, this)) {
if (Object.prototype.toString.call(stubbing.thenThat) === "[object Function]") {
return stubbing.thenThat();
} else {
return stubbing.thenThat;
}
}
i++;
}
return priorStubbing;
});
};
jasmine.Spy.prototype.whenContext = function(context) {
var addStubbing, spy;
spy = this;
spy._stealth_stubbings || (spy._stealth_stubbings = []);
whatToDoWhenTheSpyGetsCalled(spy);
addStubbing = function(thenThat) {
spy._stealth_stubbings.push({
type: 'context',
ifThis: context,
thenThat: thenThat
});
return spy;
};
return {
thenReturn: addStubbing,
thenCallFake: addStubbing
};
};
jasmine.Spy.prototype.when = function() {
var addStubbing, ifThis, spy;
spy = this;
ifThis = jasmine.util.argsToArray(arguments);
spy._stealth_stubbings || (spy._stealth_stubbings = []);
whatToDoWhenTheSpyGetsCalled(spy);
addStubbing = function(thenThat) {
spy._stealth_stubbings.push({
type: 'args',
ifThis: ifThis,
thenThat: thenThat
});
return spy;
};
return {
thenReturn: addStubbing,
thenCallFake: addStubbing
};
};
jasmine.Spy.prototype.mostRecentCallThat = function(callThat, context) {
var i;
i = this.calls.length - 1;
while (i >= 0) {
if (callThat.call(context || this, this.calls[i]) === true) {
return this.calls[i];
}
i--;
}
};
jasmine.Matchers.ArgThat = (function(_super) {
__extends(ArgThat, _super);
function ArgThat(matcher) {
this.matcher = matcher;
}
ArgThat.prototype.jasmineMatches = function(actual) {
return this.matcher(actual);
};
return ArgThat;
})(jasmine.Matchers.Any);
jasmine.Matchers.ArgThat.prototype.matches = jasmine.Matchers.ArgThat.prototype.jasmineMatches;
jasmine.argThat = function(expected) {
return new jasmine.Matchers.ArgThat(expected);
};
jasmine.Matchers.Capture = (function(_super) {
__extends(Capture, _super);
function Capture(captor) {
this.captor = captor;
}
Capture.prototype.jasmineMatches = function(actual) {
this.captor.value = actual;
return true;
};
return Capture;
})(jasmine.Matchers.Any);
jasmine.Matchers.Capture.prototype.matches = jasmine.Matchers.Capture.prototype.jasmineMatches;
Captor = (function() {
function Captor() {}
Captor.prototype.capture = function() {
return new jasmine.Matchers.Capture(this);
};
return Captor;
})();
jasmine.captor = function() {
return new Captor();
};
}).call(this);
// Jasmine.Async, v0.1.0
// Copyright (c)2012 Muted Solutions, LLC. All Rights Reserved.
// Distributed under MIT license
// http://github.com/derickbailey/jasmine.async
this.AsyncSpec = (function(global){
// Private Methods
// ---------------
function runAsync(block){
return function(){
var done = false;
var complete = function(){ done = true; };
runs(function(){
block(complete);
});
waitsFor(function(){
return done;
});
};
}
// Constructor Function
// --------------------
function AsyncSpec(spec){
this.spec = spec;
}
// Public API
// ----------
AsyncSpec.prototype.beforeEach = function(block){
this.spec.beforeEach(runAsync(block));
};
AsyncSpec.prototype.afterEach = function(block){
this.spec.afterEach(runAsync(block));
};
AsyncSpec.prototype.it = function(description, block){
// For some reason, `it` is not attached to the current
// test suite, so it has to be called from the global
// context.
global.it(description, runAsync(block));
};
return AsyncSpec;
})(this);
\ No newline at end of file
......@@ -29,8 +29,8 @@ prepend_path: common/static
# Paths to library JavaScript files (optional)
lib_paths:
- js/vendor/jquery.min.js
- js/vendor/jasmine-jquery.js
- js/vendor/jasmine-imagediff.js
- js/libs/jasmine-waituntil.js
- js/vendor/jquery.truncate.js
- js/vendor/mustache.js
- common/js/vendor/underscore.js
......
......@@ -29,8 +29,9 @@ prepend_path: common/static
# Paths to library JavaScript files (optional)
lib_paths:
- js/vendor/jquery.min.js
- js/vendor/jasmine-jquery.js
- js/vendor/jasmine-imagediff.js
- js/libs/jasmine-stealth.js
- js/libs/jasmine-waituntil.js
- js/vendor/jquery.simulate.js
- js/vendor/jquery.truncate.js
- common/js/vendor/underscore.js
......@@ -45,7 +46,6 @@ lib_paths:
- coffee/src/jquery.immediateDescendents.js
- js/vendor/requirejs/text.js
- js/vendor/sinon-1.17.0.js
- js/vendor/jasmine-stealth.js
# Paths to source JavaScript files
src_paths:
......
......@@ -34,6 +34,7 @@ var files = [
{pattern: 'js/vendor/jquery.min.js', included: true},
{pattern: 'js/vendor/jasmine-imagediff.js', included: true},
{pattern: 'js/libs/jasmine-waituntil.js', included: true},
{pattern: 'js/libs/jasmine-extensions.js', included: true},
{pattern: 'js/vendor/jquery.truncate.js', included: true},
{pattern: 'js/vendor/mustache.js', included: true},
{pattern: 'common/js/vendor/underscore.js', included: true},
......@@ -45,6 +46,7 @@ var files = [
{pattern: 'js/test/add_ajax_prefix.js', included: true},
{pattern: 'js/test/i18n.js', included: true},
{pattern: 'coffee/src/jquery.immediateDescendents.js', included: true},
{pattern: 'js/vendor/jquery.leanModal.js', included: true},
// Paths to source JavaScript files
{pattern: 'js/xblock/**/*.js', included: true, nocache: true},
......
......@@ -32,6 +32,7 @@ var files = [
{pattern: 'js/vendor/jasmine-imagediff.js', included: false},
{pattern: 'js/libs/jasmine-stealth.js', included: false},
{pattern: 'js/libs/jasmine-waituntil.js', included: false},
{pattern: 'js/libs/jasmine-extensions.js', included: false},
{pattern: 'js/vendor/jquery.simulate.js', included: false},
{pattern: 'js/vendor/jquery.truncate.js', included: false},
{pattern: 'common/js/vendor/underscore.js', included: false},
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment