vendredi 20 février 2015

Multiple Manual Mocks of CommonJS Modules with Jest

I saw the documentation for Jest's mocks using the mocks folder, but I want to be able to mock a module with one mock in one test and mock that same module with another mock in another test.


For example, with rewire and jasmine, you could do something like this:



//module2.js
module.exports = {
callFoo: function () {
require('moduleToMock').foo();
}
};

//module2Test.js
describe("test1", function () {
var mock;
beforeEach(function () {
var rewire = require('rewire');
mock = jasmine.createSpyObj('mock', ['foo']);
});
it("should be mocked with type1", function () {
mock.foo.and.returnValue("type1");
rewire('moduleToMock', mock);
var moduleUsingMockModule = require('module2');
expect(moduleUsingMockModule.callFoo()).toEqual("type1");
});
});
describe("test2", function () {
it("should be mocked with type2", function () {
mock.foo.and.returnValue("type2");
rewire('moduleToMock', mock);
var moduleUsingMockModule = require('module2');
expect(moduleUsingMockModule.callFoo()).toEqual("type2");
});
});


Is this possible to do with Jest? The difference is I define the mock within the test, not in some external folder that is used for all tests.


Aucun commentaire:

Enregistrer un commentaire