gpt4 book ai didi

javascript - 在 Jest 的函数内部模拟函数调用

转载 作者:数据小太阳 更新时间:2023-10-29 05:17:25 24 4
gpt4 key购买 nike

我有一个函数 getBookingStateObject 调用另一个函数 getBookingStateButtonsgetBookingStateButtons 又调用另外两个函数 linkBut​​tonssendEventButtons

我正在尝试为上述场景编写测试。我的测试文件中有以下内容。

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”

我是 Jest 新手,我做错了什么?

最佳答案

问题是您尝试模拟模块的某些部分,这不是 jest.mock 所做的。它所做的是模拟整个模块,在大多数情况下你想要什么。所以在你的情况下

jest.mock('getBookingStateButtons', () => jest.fn())

尝试模拟一个名为 getBookingStateButtons 的 npm 模块,所以你想像这样安装

import getBookingStateButtons from 'getBookingStateButtons'

您应该将模块视为一个黑盒子,您可以在其中放入东西并取出东西。你不能只改变黑盒子的一部分。因为我不知道 './bookingStates' 是什么,我假设它会有一些副作用,也就是与其他导入模块的一些交互。这些是你应该模拟和测试的,它们是用正确的参数调用的,而不是 './bookingStates' 模块的内部结构。

关于javascript - 在 Jest 的函数内部模拟函数调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49942866/

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