如何使用Jest模拟仅一个测试文件的模块?

jpe*_*nna 3 unit-testing jestjs

我正在使用Jest,并且想从另一个模块中模拟一些功能(我们称之为dependency)。

我能够进行dependency 全局模拟,将其放入__mocks__文件__tests__夹中的文件夹中。

Unfortunately, I need the actual dependecy for all the other tests. So, how can I specify that I want to require the mocked dependecy only when required in my file1.js, but not in all other files?

PS: I could create a __mocks__ folder inside my file1.js folder, but this file is in the root, so when dependency is required by any file it will be picked up from the __mocks__.

And*_*rle 5

您需要使用jest.mock

jest.mock('path/to/dependency', () => 'someMockValue')
Run Code Online (Sandbox Code Playgroud)

请注意,该路径是相对于测试文件的,而不是相对于您要测试的文件的路径。