Jacob
Jacob

Reputation: 301

How to mock multiple values from a mocked module?

I am trying to mock the module 'jwt-decode' and I can successfully mock one return value using the following:

 jest.mock('jwt-decode', () => () => ({ data: { userRole: 2, checklist: mockUser.account.checklist }}))

This works for one test that needs the decoded jwt to yield a userRole of 2. However, my next test needs the userRole to be one and this is where the issue arises.

Is there a proper way to return the userRole as 2 for the first instance of the test and 1 for the next instance of the test?

Upvotes: 1

Views: 300

Answers (1)

Oleksandr Sakun
Oleksandr Sakun

Reputation: 462

You can change mock implementation of your mocked function per test by calling mockImplementation or mockImplementationOnce on your mocked function with new implementation as a parameter, here is the details: https://jestjs.io/docs/en/mock-functions#mock-implementations

In your case it would be something like that:

import jwt_decode from 'jwt-decode';

jest.mock('jwt-decode', () => jest.fn(() => ({
    data: { userRole: 2, checklist: mockUser.account.checklist },
})));

it('should test behavior with userRole equal to 2', () => {
    // your test here 
});

it('here we update mock implementation and test behavior with userRole equal to 1', () => {
    jwt_decode.mockImplementationOnce(() => ({
        data: { userRole: 1, checklist: mockUser.account.checklist },
    }));
    // your test here
});

it('since we used mockImplementationOnce method in the test above, here we again will be using initial mock implementation - userRole equal to 2', () => {
    // your test here
});

Upvotes: 1

Related Questions