Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between unmock and dontMock in Jest

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?

like image 985
dooburt Avatar asked Apr 12 '16 11:04

dooburt


1 Answers

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.

like image 152
dooburt Avatar answered Oct 20 '22 09:10

dooburt