Skip to content

Instantly share code, notes, and snippets.

@alistairjcbrown
Created December 21, 2014 00:11
Show Gist options
  • Save alistairjcbrown/367636843ff91aa24c48 to your computer and use it in GitHub Desktop.
Save alistairjcbrown/367636843ff91aa24c48 to your computer and use it in GitHub Desktop.
/**
* My Module Tests
*/
define([ "squire", "sinon", "chai", "sinon-chai", "mocks/my_dependency" ],
function(Squire, sinon, chai, sinon_chai, my_dependency_mock) {
"use strict";
var expect = chai.expect;
chai.use(sinon_chai);
suite("My Module", function() {
var my_module;
suiteSetup(function(done) {
var injector = new Squire();
injector.mock("my_dependency", my_dependency_mock);
injector.require(["my_module"], function(my_module_stubbed) {
my_module = my_module_stubbed;
done();
});
});
suite("Foo", function() {
test("should exist", function() {
expect(my_module.foo).to.be.a("function");
});
test("should call `foo` on my_dependency", function() {
my_module.foo();
expect(my_dependency.foo).to.have.been.calledOnce;
});
});
});
});
@alistairjcbrown
Copy link
Author

This is an example of using Squire.js to mock a module dependency when using RequireJS as the module loader. In this example the mocha test framework is used.

The key to using Squire.js to mock module dependencies when testing is:

  1. Don't include the module to be tested as a dependency of the test
  2. Use mocha's suiteSetup and asynchronous done callback to first mock the dependency using Squire.js and then require the module to be tested using Squire.js.
  3. Expose the module required with Squire.js, which is now using a mock dependency, by assigning it to a variable declared in the scope of the suite.

A use case for this kind of mocking is when the dependency has an unwanted affect when called, eg. starting a server. In this case, the server module can be mocked, either to prevent the server starting, or to confirm that the correct data is provided to the server module.

This was used in alistairjcbrown/redis-websocket-event-proxy to stub the HTTP server, websocket server and redis client, but to confirm that communication between these systems was correct.

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