Multiple Manual Mocks of CommonJS Modules with Jest
jestjs, mocking, unit-testing
Solution
Yes, your mock will look like this:
module.exports = {
foo: jest.genMockFunction();
}
Then you will be able to configure a custom behaviour in your test cases:
var moduleToMock = require('moduleToMock');
describe('...', function() {
it('... 1', function() {
moduleToMock.foo.mockReturnValue('type1')
expect(moduleToMock.foo).toBeCalled();
expect(moduleUsingMockModule.callFoo()).toEqual("type1");
});
it('... 2', function() {
moduleToMock.foo.mockReturnValue('type2')
expect(moduleToMock.foo).toBeCalled();
expect(moduleUsingMockModule.callFoo()).toEqual("type2");
});
});
Problem
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.