gpt4 book ai didi

javascript - 开 Jest 不尊重导入模块的模拟

转载 作者:行者123 更新时间:2023-11-29 23:24:42 24 4
gpt4 key购买 nike

// 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')
})

我希望我的 console.log 显示 theFuncIWantToMock 是一个 mock 实例,但我看到的是原来的定义的功能。根据 Jest 文档,这就是我应该模拟模块的方式。但这似乎不起作用。

最佳答案

从“someModule”导入 theFuncIWantToMock

您正在导入默认模块

所以这意味着您需要模拟默认设置。尝试将其更改为此。

jest.mock('someModule', () => jest.fn());

模拟文件的另一种方法是在模块所在位置附近的 __mocks__ 下创建文件。

__mocks__/someModule.js 里面

const mockFunc = jest.fn();
export default mockFunc;

在你的测试函数中

jest.mock('someModule');

如果这些不是 node_modules,也可以尝试使用相对路径。 https://facebook.github.io/jest/docs/en/manual-mocks.html#mocking-node-modules

关于javascript - 开 Jest 不尊重导入模块的模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49662673/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com