Jest: Manual user mocks not working with custom resolver

Created on 5 Sep 2017  路  6Comments  路  Source: facebook/jest


Do you want to request a feature or report a bug?

Bug 馃悶

What is the current behavior?

Given I have this jest config:

{
  "resolver": "<rootDir>/customResolver"
}

And a module <rootDir>/index.js
And a manual mock available in <rootDir>/__mocks__/index.js
And a spec file mocking the <rootDir>/index.js module
Then I expect the mocked module to be loaded in other modules and my spec
BUT the original module is still being loaded

When I remove the resolver option in my jest config
Then everything works as expected

If the current behavior is a bug, please provide the steps to reproduce and either a repl.it demo through https://repl.it/languages/jest or a minimal repository on GitHub that we can yarn install and yarn test.

https://github.com/Xiphe/jest-custom-resolver-with-mocks

What is the expected behavior?

When I use jest.mock to mock a user module file
Then I expect the mocked module to be loaded
Even If I use a custom resolver

Please provide your exact Jest configuration and mention your Jest, node, yarn/npm version and operating system.

Minimal jest config to reproduce this error:

{
  "resolver": "<rootDir>/customResolver"
}

customResolver.js

module.exports = require('jest-resolve/build/default_resolver');

Versions

  • jest: 21.0.1
  • node: 8.4.0
  • npm: 5.4.0
  • OS: macOS 10.12.6

Most helpful comment

I have a fix. Just adding a test, and then will create PR

All 6 comments

This has been introduced with https://github.com/facebook/jest/pull/4174 (https://github.com/facebook/jest/commit/de74b38aff9f0a91dcdaf5986d2a6f963b78cfdf)

When I revert that change and link jest-resolve in my project, everything works as expected.

cc @midzelis

I'll take a look. Could be a few days before I have something.

I have a fix. Just adding a test, and then will create PR

Thanks for caring @midzelis!

Sorry to comment on an old issue, but i'm having this problem.

Is there an example of a simple resolver that does not have this problem?

custom resolver:

const { NodeJsInputFileSystem, CachedInputFileSystem, ResolverFactory } = require("enhanced-resolve");

const resolver = ResolverFactory.createResolver({
        fileSystem: new CachedInputFileSystem(new NodeJsInputFileSystem(), 4000),
        useSyncFileSystemCalls: true,
// add src to mainFields so we don't need to build local packages before testing
        mainFields: ['src', 'main']
});

module.exports = function(value, options) {
  return resolver.resolveSync({}, options.basedir, value);
};

test snippet

jest.mock('../../src/interpolateValues');
import interpolateValues from '../../src/interpolateValues';
...
interpolateValues.mockImplementation(() => ({ foo: 'hello' }));

error
TypeError: _interpolateValues2.default.mockImplementation is not a function

Was this page helpful?
0 / 5 - 0 ratings