Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 527
Sooraj Avatar asked Apr 20 '18 13:04

Sooraj


People also ask

How do you mock a function inside a function?

You can mock functions in two ways: either you create a mock function to use in test code, or you write a manual mock that overrides a module dependency. Let's take for example the case where we're testing an implementation of a function forEach, which will invoke a callback for each item in a supplied array.

How do you call a function inside a function in Jest?

You can create a namespace that you export as the default object and call b using the namespace. This way, when you call jest. mock it will replace the b function on the namespace object. const f = require('./f'); jest.


1 Answers

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.

like image 113
Andreas Köberle Avatar answered Sep 20 '22 15:09

Andreas Köberle