A few manual layouts of CommonJS modules with a joke

I saw the documentation for Jest mocks using the mocks folder, but I want to wind a module with one layout in one test and mock the same module with a different layout in another test.

For example, with rewire and jasmine, you can 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"); }); }); 

Can this be done with Jest? The difference is that I define the layout in the test, and not in some external folder that is used for all tests.

+2
unit-testing mocking jestjs
source share
1 answer

Yes, your layout will look like this:

 module.exports = { foo: jest.genMockFunction(); } 

Then you can customize your behavior 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"); }); }); 
+1
source share

All Articles