在 Jest 中模拟函数内的函数调用 [英] Mocking a function call inside a function in Jest
问题描述
我有一个函数 getBookingStateObject
调用另一个函数 getBookingStateButtons
.getBookingStateButtons
依次调用另外两个函数 linkButtons
和 sendEventButtons
.
I have a function getBookingStateObject
that calls another function getBookingStateButtons
. In turn getBookingStateButtons
calls two other functions linkButtons
and sendEventButtons
.
我正在尝试为上述场景编写测试.我的测试文件中有以下内容.
I'm trying to write tests for the above scenario. I have the following in my test file.
import {
getBookingStateButtons,
getBookingStateObject,
linkButtons,
sendEventButtons,
} from './bookingStates'
jest.mock('getBookingStateButtons', () => jest.fn())
jest.mock('linkButtons', () => jest.fn())
jest.mock('sendEventButtons', () => jest.fn())
it('calls getBookingStateButtons, linkButtons, sendEventButtons', () => {
getBookingStateObject({ aasm_state: 'created' }, '123')
expect(getBookingStateButtons).toHaveBeenCalledWith({
bookingId: '123',
events: [{ event: 'mark_requested', type: 'secondary' }],
links: [{ to: 'edit' }],
})
expect(linkButtons).toHaveBeenCalledWith({
to: 'edit',
type: 'secondary',
})
expect(sendEventButtons).toHaveBeenCalledWith({
event: 'mark_requested',
type: 'secondary',
})
})
当我运行测试时,我收到以下错误:无法从bookingStates.spec.tsx"中找到模块getBookingStateButtons"
When I run the tests I get the following error:
Cannot find module 'getBookingStateButtons' from 'bookingStates.spec.tsx'
我是个新手,我做错了什么?
I'm new to jest, What am I doing wrong?
推荐答案
问题在于您尝试模拟模块的某些部分,而这不是 jest.mock
所做的.它所做的是模拟整个模块,在大多数情况下你想要什么.所以在你的情况下
The problem is that you try to mock parts of module which is not what jest.mock
does. What it does is to mock the whole module, what is what you want in most of the cases. So in your case
jest.mock('getBookingStateButtons', () => jest.fn())
试图模拟一个名为 getBookingStateButtons
的 npm 模块,所以你想像这样安装一些东西
tries to mock an npm module with the name getBookingStateButtons
, so something that you want to install like this
import getBookingStateButtons from 'getBookingStateButtons'
您应该将模块视为一个黑匣子,您可以在其中放入东西并取出东西.你不能只改变黑匣子的一部分.由于我不知道 './bookingStates'
是什么,我假设它会有一些副作用,也就是与其他导入模块的一些交互.这些是你应该模拟和测试的,它们在调用时使用了正确的参数,而不是 './bookingStates'
模块的内部结构.
You should think about a module as a black box where you put stuff in and get something out. You can't just change parts of the black box. As I don't know what the './bookingStates'
, I assume that it will have some side effects, aka some interactions with other imported modules. These are ones you shoudl mock and test that they where called with teh correct parameter, not the internals of the './bookingStates'
module.
这篇关于在 Jest 中模拟函数内的函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!