简体   繁体   中英

Mocking a function call inside a function in Jest

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

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?

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())

tries to mock an npm module with the name getBookingStateButtons , so something that you want to install like this

import getBookingStateButtons from 'getBookingStateButtons'

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM