Skip to content

Instantly share code, notes, and snippets.

@danscotton
Created July 27, 2012 12:50
Show Gist options
  • Save danscotton/3187758 to your computer and use it in GitHub Desktop.
Save danscotton/3187758 to your computer and use it in GitHub Desktop.
Mocking an AMD dependency that returns a constructor with sinon.js
// 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'
}));
});
});
@danscotton
Copy link
Author

When a VideoLoader object is instantiated using new VideoLoader(domElement, metaObject), the constructor function calls this.embedEmp() which calls new Emp(), passing it a config object.

Emp is defined as a dependency of VideoLoader. The only way we've found to be able to mock this dependency properly, is to pass in an optional Emp stub to VideoLoader and then redefine it on line: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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment