Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jest mock: how to use real module in a particular test?

Tags:

jestjs

I try to mock some node modules for most of the tests, according to the doc I put the mock files into __mocks__ folder, but I also want to use the real module in a particular test, I have tried jest.unmock('some-module') but not working.

this is my project structure:

├──__mocks__
│   └── foo.js
│──doSomething.js
│──test.js

__mocks__/foo.js

const foo = jest.genMockFromModule('foo');
module.exports = foo;

doSomething.js

const foo = require('foo');

const doSomething = () => {
  foo.bar();
};

module.exports = doSomething;

test.js

const doSomething = require('./doSomething');

describe('Test', () => {
  it('doSomething() should call foo.bar', () => {
    doSomething();

    expect(foo.bar).toBeCalled();
  })

  it('use real foo module', () => {
    // How could I use real foo module in this test?

    jest.unmock('some-module'); // not working
    doSomething();
  })

})

1 Answers

You can use requireActual to bypass the mocked module:

const doSomething = jest.requireActual('some-module');
doSomething();

Docs: https://jestjs.io/docs/en/bypassing-module-mocks

like image 139
Steve Holgado Avatar answered Sep 05 '25 16:09

Steve Holgado



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!