Reputation: 10567
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?
Upvotes: 10
Views: 15726
Reputation: 110892
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.
Upvotes: 7