Created
July 27, 2012 12:50
-
-
Save danscotton/3187758 to your computer and use it in GitHub Desktop.
Mocking an AMD dependency that returns a constructor with sinon.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// GOAL: | |
// To test that VideoLoader creates Emp with the correct parameters. | |
/** | |
* VideoLoader (module/media/videoLoader) | |
* - has Emp (a bbc video player) as a dependency | |
*/ | |
define(['module/media/emp'], function(Emp) { | |
var VideoLoader = function(placeholder, meta, EmpStub) { | |
this.placeholder = placeholder; | |
this.meta = meta; | |
Emp = EmpStub || Emp; // <-- set Emp to a stub if one gets passed in as the 3rd parameter | |
// ... | |
this.embedEmp(); | |
}; | |
VideoLoader.prototype.embedEmp = function() { | |
var emp = new Emp({ | |
playlist: this.meta.href, | |
id: this.meta.id | |
}); | |
}; | |
return VideoLoader; | |
}); | |
/** | |
* VideoLoader test | |
*/ | |
define(['module/media/videoLoader'], function(VideoLoader) { | |
module('VideoLoader', { | |
setup: function() { | |
this.placeholder = $('#qunit-fixture .placeholder'); | |
this.fakeMeta = { | |
href: 'playlists.bbc.co.uk', | |
id: '12345' | |
} | |
} | |
}); | |
test('should create an Emp object with the correct parameters', function() { | |
var empSpy = sinon.spy(); | |
var videoLoader = new VideoLoader(this.placeholder, this.meta, empSpy); // <-- pass in spy using constructor injection | |
ok(empSpy.calledWithNew()); | |
ok(empSpy.calledWith({ | |
playlist: 'playlists.bbc.co.uk', | |
id: '12345' | |
})); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
When a
VideoLoader
object is instantiated usingnew VideoLoader(domElement, metaObject)
, the constructor function callsthis.embedEmp()
which callsnew Emp()
, passing it a config object.Emp
is defined as a dependency ofVideoLoader
. The only way we've found to be able to mock this dependency properly, is to pass in an optionalEmp
stub toVideoLoader
and then redefine it online:14
. That way, we have a handle to the spy in our tests that we can inspect.Would you recommend this approach, or is there a better way to mock a dependency and get a handle on it to check within the tests?