It seems that the jest.autoMockOff fn fails to work when your tests are written with es6 imports. the imports don't use the default require when compiled with babel, and therefore your override of the require function isn't used. Can Jest tap into babel's importer when it's available?
It does not work, because
jest.autoMockOff()
import foo from './foo'
is compiled to
'use strict';
function _interopRequireDefault(obj) {return obj && obj.__esModule ? obj : { 'default': obj };}
var _foo = require('./foo');
var _foo2 = _interopRequireDefault(_foo);
jest.autoMockOff();
Notice that jest.autoMockOff() is after require.
Yeah, imports are hoisted (see https://github.com/babel/babel-jest/issues/16), so workaround is to use explicit require here. See also https://github.com/facebook/jest/pull/379. Closing this one.
An alternative workaround (suggested by @rauschma) can be found here.
import '../auto_mock_off';
import foo from './foo'
where '../auto_mock_off' is a module containing:
jest.autoMockOff();
For future reference, the new API we introduced together with babel-jest from 0.9 onwards is jest.disableAutomock().
would hoisting jest.disableAutomock() as the last step work?
We do hoist jest.disableAutomock() :)
I encountered a similar issue with jest.useFakeTimers(). The following test works fine:
jest.useFakeTimers();
const Promise = require('bluebird');
describe('test', () => {
it('should call mock function', () => {
const fn = jest.fn();
Promise.resolve(1).then(fn);
jest.runAllTimers();
expect(fn.mock.calls).toEqual([[ 1 ]]);
});
});
If I replaced the require call with import Promise from 'bluebird', the test would fail.
Most helpful comment
An alternative workaround (suggested by @rauschma) can be found here.
where
'../auto_mock_off'is a module containing: