簡體   English   中英

在Jest中的函數內模擬函數調用

[英]Mocking a function call inside a function in Jest

我有一個函數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'

我是開玩笑的新手,我做錯了什么?

問題是你試圖模擬不是jest.mock所做的模塊部分。 它的作用是模擬整個模塊,在大多數情況下你想要什么。 所以在你的情況下

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

嘗試使用名稱getBookingStateButtons來模擬一個npm模塊,所以你要安裝這樣的東西

import getBookingStateButtons from 'getBookingStateButtons'

你應該把模塊想象成一個黑盒子,你把東西放進去,然后把東西拿出去。 你不能只改變黑匣子的部分。 由於我不知道'./bookingStates'是什么,我認為它會產生一些副作用,也就是與其他導入模塊的一些交互。 這些是你要模擬並測試它們在哪里用正確的參數調用,而不是'./bookingStates'模塊的內部。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM