在Jest中的函数内模拟函数调用

时间:2018-04-20 13:33:04

标签: javascript unit-testing jestjs

我有一个函数getBookingStateObject,可以调用另一个函数getBookingStateButtons。反过来getBookingStateButtons会调用另外两个函数linkButtonssendEventButtons

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

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'

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

1 个答案:

答案 0 :(得分:5)

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

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

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

import getBookingStateButtons from 'getBookingStateButtons'

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

相关问题