Mat*_*att 5 javascript reactjs jestjs
// fileImTestingAgainst.js
import theFuncIWantToMock from 'someModule'
export default function whatever () {
// logging for debugging purposes
console.log(theFuncIWantToMock)
const myVar = theFuncIWantToMock(/* args */)
// ... more stuff
}
// myTest.js
jest.mock('someModule', () => ({
theFuncIWantToMock: jest.fn()
}))
import theFuncIWantToMock from 'someModule'
import whatever from 'fileImTestingAgainst'
test('do my test', () => {
whatever()
expect(theFuncIWantToMock).toHaveBeenCalledWith('cat')
})
Run Code Online (Sandbox Code Playgroud)
我希望我console.log能显示它theFuncIWantToMock是一个mock实例,但我显示的是最初定义的函数。根据 Jest 文档,这就是我应该模拟模块的方式。但这似乎不起作用。
import theFuncIWantToMock from 'someModule'
您正在导入默认模块
所以这意味着您需要模拟默认值。尝试将其更改为这样。
jest.mock('someModule', () => jest.fn());
__mocks__模拟文件的另一种方法是在模块所在位置附近创建文件。
里面__mocks__/someModule.js
const mockFunc = jest.fn();
export default mockFunc;
Run Code Online (Sandbox Code Playgroud)
在你的测试函数中
jest.mock('someModule');
Run Code Online (Sandbox Code Playgroud)
如果这些不是node_modules,也尝试使用相对路径。 https://facebook.github.io/jest/docs/en/manual-mocks.html#mocking-node-modules
| 归档时间: |
|
| 查看次数: |
2752 次 |
| 最近记录: |