Monday, May 20, 2024
47
rated 0 times [  51] [ 4]  / answers: 1 / hits: 95906  / 7 Years ago, mon, july 10, 2017, 12:00:00

I am quite confused with mocking in Jest an how to unit test the implementations. The thing is i want to mock different expected behaviours.



Is there any way to achieve this? as imports can be only on the top of the file and to be able to mock something it must be declared before the import. I have also tried to pass a local function so I could overwrite the behaviour but jest complains you are not allowed to pass anything local.



jest.mock('the-package-to-mock', () => ({
methodToMock: jest.fn(() => console.log('Hello'))
}));

import * as theThingToTest from '../../../app/actions/toTest'
import * as types from '../../../app/actions/types'

it('test1', () => {
expect(theThingToTest.someAction().type).toBe(types.SOME_TYPE)
})

it('test2', () => {
//the-package-to-mock.methodToMock should behave like something else
expect(theThingToTest.someAction().type).toBe(types.SOME_TYPE)
})


internally as you can imagine theThingToTest.someAction() uses the-package-to-mock.methodToMock


More From » react-native

 Answers
16

You can mock with a spy and import the mocked module. In your test you set how the mock should behave using mockImplementation:


jest.mock('the-package-to-mock', () => ({
methodToMock: jest.fn()
}));
import { methodToMock } from 'the-package-to-mock'

it('test1', () => {
methodToMock.mockImplementation(() => 'someValue')
})

it('test2', () => {
methodToMock.mockImplementation(() => 'anotherValue')
})

[#57145] Friday, July 7, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tristab

Total Points: 735
Total Questions: 106
Total Answers: 96

Location: Grenada
Member since Sun, Dec 20, 2020
3 Years ago
;