即使在测试中未使用 jest.mock('request-promise-native') 时,Jest 手动模拟始终用于 request-promise-native
Jest manual mock always used for request-promise-native even when jest.mock('request-promise-native') is not used in test used
我的测试中始终使用模拟的 'request-promise-native' 模块,即使 jest.mock("request-promise-native") 被注释掉也是如此。
项目结构如下:
project
└───__mocks__
│ └───request-promise-native.js
└───node_modules
│ │ folder1
│ │ ...
│ └───request-promise-native
│ │ │ lib
│ │ │ ...
└───src
│ │ file1
│ │ ...
└───test
└───sometest.test.js
在sometest.test.js中,我使用jest.mock("request-promise-native");
,这成功地使用了request-promise-native的模拟版本(通过在模拟版本中使用console.log证明)。
我在sometest.test.js中注释掉jest.mock("request-promise-native");
的时候,还在用mock版?!
我的印象是 jest automock 选项默认设置为 false 所以它应该使用模块的实际版本?
为了弄清楚这一切,我在配置文件中将 automock 选项设置为 false,结果还是一样。
我可以获得要使用的实际版本的唯一方法是将 jest.mock("request-promise-native");
替换为 jest.unmock("request-promise-native");
或重命名 mock 中的 request-promise-native.js 所以没被jest看到
这是开玩笑的错误还是我的设置错误?
我还有其他私有模块的手动模拟,它的行为符合预期:当 jest.mock() 出现时使用模拟版本,当 jest.mock 注释掉时使用原始版本。
我找到了一个类似问题的错误报告https://github.com/facebook/jest/issues/1552,但它似乎已经在不久前解决了。
发生这种情况是因为我试图模拟 node_modules 文件夹中的模块吗?
任何帮助都会很好,因为我希望能够控制使用哪个版本的模块(单元测试模拟,集成测试正常)并且有信心知道模拟模块是仅在我使用 jest.mock().
时使用
Jest
表现符合预期。
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')
.
所以是的,你完全正确。节点模块 自动 模拟,此行为不同于需要调用 [=16= 的用户模块或节点核心模块(如 fs
或 path
) ].
我的测试中始终使用模拟的 'request-promise-native' 模块,即使 jest.mock("request-promise-native") 被注释掉也是如此。
项目结构如下:
project
└───__mocks__
│ └───request-promise-native.js
└───node_modules
│ │ folder1
│ │ ...
│ └───request-promise-native
│ │ │ lib
│ │ │ ...
└───src
│ │ file1
│ │ ...
└───test
└───sometest.test.js
在sometest.test.js中,我使用jest.mock("request-promise-native");
,这成功地使用了request-promise-native的模拟版本(通过在模拟版本中使用console.log证明)。
我在sometest.test.js中注释掉jest.mock("request-promise-native");
的时候,还在用mock版?!
我的印象是 jest automock 选项默认设置为 false 所以它应该使用模块的实际版本?
为了弄清楚这一切,我在配置文件中将 automock 选项设置为 false,结果还是一样。
我可以获得要使用的实际版本的唯一方法是将 jest.mock("request-promise-native");
替换为 jest.unmock("request-promise-native");
或重命名 mock 中的 request-promise-native.js 所以没被jest看到
这是开玩笑的错误还是我的设置错误? 我还有其他私有模块的手动模拟,它的行为符合预期:当 jest.mock() 出现时使用模拟版本,当 jest.mock 注释掉时使用原始版本。
我找到了一个类似问题的错误报告https://github.com/facebook/jest/issues/1552,但它似乎已经在不久前解决了。
发生这种情况是因为我试图模拟 node_modules 文件夹中的模块吗?
任何帮助都会很好,因为我希望能够控制使用哪个版本的模块(单元测试模拟,集成测试正常)并且有信心知道模拟模块是仅在我使用 jest.mock().
时使用Jest
表现符合预期。
If the module you are mocking is a Node module...the mock should be placed in the
__mocks__
directory adjacent tonode_modules
...and will be automatically mocked. There's no need to explicitly calljest.mock('module_name')
.
所以是的,你完全正确。节点模块 自动 模拟,此行为不同于需要调用 [=16= 的用户模块或节点核心模块(如 fs
或 path
) ].