Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking require statements with Jest

Tags:

sum.js

module.exports = function sum(a, b){     return a + b; }; 

Thing.js

var sum = require("./sum");  module.exports = class Thing {     add(a, b){         return sum(a, b);     } } 

Thing.test.js

test('1 + 2 = 3', () => {     //Arrange     var Thing = require('./Thing');     var thing = new Thing();      //Act     var result = thing.add(1, 2);      //Assert     expect(result).toBe(3); });  test('sum mocked', () => {     //Arrange     jest.mock('./sum', () => {         return jest.fn(() => 42);     });      var Thing = require('./Thing');     var thing = new Thing();      //Act     var result = thing.add(1, 2);      //Assert     expect(result).toBe(42); }); 

How can I mock the sum 'require' dependency when testing? I get the following error.

sum mocked      expect(received).toBe(expected)      Expected value to be (using ===):       42     Received:       3 

What's interesting if I run each test individually with .only, they both work just fine on their own.

In the past I've used proxyquire to do things like this but I'd like to avoid it if possible.

like image 768
RoboKozo Avatar asked Mar 10 '17 23:03

RoboKozo


1 Answers

In the test, I added

beforeEach(() =>  {     jest.resetModules(); }); 

and the tests passed as expected.

like image 163
RoboKozo Avatar answered Sep 29 '22 11:09

RoboKozo