我试图用Jest的模块中的单个功能模拟一个单个功能,并断言我已经使用某些参数调用了它。我有一个大致看起来像这样的文件:
export const f = () => {
...
}
export const g = () => {
...
f(...)
}
export const h = () => {
...
g(...)
}
我正在尝试测试功能 g
和 h
,而我要编写的断言是 f
在调用 g
和 h
时,请使用某些参数调用。因此,在我的测试中,我想模拟 f
,并能够断言它的所谓。但是,当我在测试中进行类似的事情时:
import f, g, h from 'module'
jest.mock('module', () => {
const original = jest.requireActual('module')
return {
...original,
f: jest.fn()
}
})
test('g calls f correctly', () => {
g()
// I want to assert that f was called with some parameters
})
我没有提到 f
,并且似乎当 g
在测试中调用时,实际函数 f
被称为而不是模拟。我需要在这里进行什么才能实现此功能?
I'm trying to mock out a single function in a module with Jest and assert that I have called it with certain parameters. I have a file that roughly looks like so:
export const f = () => {
...
}
export const g = () => {
...
f(...)
}
export const h = () => {
...
g(...)
}
I'm trying to test out functions g
and h
, and one the assertions I'm trying to write is that f
gets called with certain parameters when calling g
and h
. So in my tests, I want to mock out f
and be able to assert what it was called with. However, when I do something like this in my tests:
import f, g, h from 'module'
jest.mock('module', () => {
const original = jest.requireActual('module')
return {
...original,
f: jest.fn()
}
})
test('g calls f correctly', () => {
g()
// I want to assert that f was called with some parameters
})
I have no reference to f
, and it seems like when g
gets called in the test, the actual function f
is being called rather than a mock. What do I need to change here to get this working?
发布评论
评论(1)
看起来您走在正确的道路上。我建议您尝试以下示例之一:
如果您遇到错误,说
f
应该是模拟功能,则可以尝试以下操作:It looks like you're on the right path. I'll recommend you try one of the following examples:
If you get an error saying that
f
should be a mock function, you could try this: