模拟Jest中模块中的单个函数并对其进行断言



我试图用Jest模拟模块中的单个函数,并断言我已经用某些参数调用了它。我有一个文件,大致如下所示:

export const f = () => {
...
}
export const g = () => {
...
f(...)
}
export const h = () => {
...
g(...)
}

我试图测试函数gh,我试图写的断言之一是f在调用gh时被调用某些参数。因此,在我的测试中,我想模拟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被调用,而不是模拟。我需要在这里做什么改变才能让它工作?

看来你选对了。我建议你试试下面的一个例子:

import { f, g } from './module'
jest.mock('./module', () => {
const actual = jest.requireActual()
return { ...actual, f: jest.fn() }
})
test('g calls f correctly', () => {
g()
expect(f).toHaveBeenCalled()
})

如果您得到一个错误,说f应该是一个模拟函数,您可以尝试:

import { g } from './module'
// Create a reference of the mocked function to use later in the test.
// The name must start with "mock". It's a Jest rule.
const mockedF = jest.fn()
jest.mock('./module', () => {
const actual = jest.requireActual()
return { ...actual, f: mockedF }
})
test('g calls f correctly', () => {
g()
expect(mockedF).toHaveBeenCalled()
})

最新更新