【问题标题】:Mocking a function call inside a function in Jest在 Jest 中模拟函数内部的函数调用
【发布时间】:2018-10-01 05:50:24
【问题描述】:

我有一个函数getBookingStateObject,它调用另一个函数getBookingStateButtons。依次getBookingStateButtons 调用另外两个函数linkButtons 和sendEventButtons。

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

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

当我运行测试时,我收到以下错误: Cannot find module 'getBookingStateButtons' from 'bookingStates.spec.tsx'

我是开玩笑的新手,我做错了什么?

【问题讨论】:

    标签: javascript unit-testing jestjs


    【解决方案1】:

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

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

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

    import getBookingStateButtons from 'getBookingStateButtons'
    

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

    【讨论】:

    • bookingStates 是我自己搭建的一个模块。
    猜你喜欢
    • 2021-08-27
    • 1970-01-01
    • 2018-12-18
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多