Jest manual mock always used for request-promise-native even when jest.mock('request-promise-native') is not used in test used

问题: The mocked 'request-promise-native' module is always used in my test even when jest.mock("request-promise-native") is commented out. The project structure is as follow:...

问题:

The mocked 'request-promise-native' module is always used in my test even when jest.mock("request-promise-native") is commented out.

The project structure is as follow:

project
└───__mocks__
│   └───request-promise-native.js
└───node_modules
│   │   folder1
│   │   ...
│   └───request-promise-native
│   │   │   lib
│   │   │   ...
└───src
│   │   file1
│   │   ...
└───test
    └───sometest.test.js

In sometest.test.js, I use jest.mock("request-promise-native"); and this successfully uses the mock version of request-promise-native (proven by using console.log in the mock version).

When I comment out jest.mock("request-promise-native"); in sometest.test.js, the mock version is still used?! I was under the impression jest automock option is set to false by default so it should use the actual version of the module?

To try to make sense of it all, I set the automock option to false in the configuration file and it is still the same.

The only way I can get the actual version to be used is to replace jest.mock("request-promise-native"); with jest.unmock("request-promise-native"); or rename the request-promise-native.js in mock so it is not seen by jest.

Is this a bug with jest or my setup? I have other manual mocks of private modules and it behaves as expected: mock version used when jest.mock() present and original version used when jest.mock commented out.

I have found a bug report for a similar issue https://github.com/facebook/jest/issues/1552 but it seems to have been resolved a while ago.

Is this happening because I'm trying to mock a module in the node_modules folder?

Any help with this would be great as I would like to be able to control which version of the module is used (mock for unit test, normal for integration tests) and also to have the confidence to know mocked modules are only used when I use jest.mock().


回答1:

Jest is behaving as expected.

See Mocking Node modules:

If the module you are mocking is a Node module...the mock should be placed in the __mocks__ directory adjacent to node_modules...and will be automatically mocked. There's no need to explicitly call jest.mock('module_name').

So yes, you are exactly right. Node modules are automatically mocked and this behavior is different than user modules or Node core modules (like fs or path) which require a call to jest.mock.

  • 发表于 2019-03-03 12:25
  • 阅读 ( 760 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除