Difference between unmock and dontMock in Jest

12,873

This is covered in the Jest documentation.

Seems that we should all use unmock now to prevent hoisting of the mocked to above the ES6 import:

I'm using babel and my unmocked imports aren't working?

Upgrade jest-cli to 0.9.0.

Explanation:

jest.dontMock('foo');

import foo from './foo';

In ES2015, import statements get hoisted before all other

var foo = require('foo'); jest.dontMock('foo'); // Oops!

In Jest 0.9.0, a new API jest.unmock was introduced. Together with a plugin for babel, this will now work properly when using babel-jest:

jest.unmock('foo'); // Use unmock!

import foo from './foo';

// foo is not mocked!

See the Getting Started guide on how to enable babel support.

Share:
12,873
dooburt
Author by

dooburt

Butterside up my friend.

Updated on June 17, 2022

Comments

  • dooburt
    dooburt almost 2 years

    So I've been writing a successful unit test library and all seems well. And then I noticed in some online examples that where I do this:-

    jest.unmock('../lib/q');

    Others do this:-

    jest.dontMock('../lib/q');

    I can't find any documentation on the Jest site (the documentation isn't great let's be honest), so I changed one of my suites for a giggle to dontMock and quite a lot exploded ... What's the difference?

  • Joe Clay
    Joe Clay about 8 years
    As of just a few hours ago, it seems like the issue with imports being hoisted above dontMock has been fixed: facebook.github.io/jest/blog/2016/04/12/jest-11.html