how to change jest mock function return value in each test? how to change jest mock function return value in each test? reactjs reactjs

how to change jest mock function return value in each test?


You can mock the module so it returns spies and import it into your test:

import {navigationEnabled, guidanceEnabled} from '../../../magic/index'jest.mock('../../../magic/index', () => ({    navigationEnabled: jest.fn(),    guidanceEnabled: jest.fn()}));

Then later on you can change the actual implementation using mockImplementation

navigationEnabled.mockImplementation(()=> true)//ornavigationEnabled.mockReturnValueOnce(true);

and in the next test

navigationEnabled.mockImplementation(()=> false)//ornavigationEnabled.mockReturnValueOnce(false);


what you want to do is

import { navigationEnabled, guidanceEnabled } from '../../../magic/index';   jest.mock('../../../magic/index', () => ({  navigationEnabled: jest.fn(),  guidanceEnabled: jest.fn()}));describe('test suite', () => {  it('every test', () => {    navigationEnabled.mockReturnValueOnce(value);    guidanceEnabled.mockReturnValueOnce(value);  });});

you can look more about these functions here =>https://facebook.github.io/jest/docs/mock-functions.html#mock-return-values


I had a hard time getting the accepted answers to work - my equivalents of navigationEnabled and guidanceEnabled were undefined when I tried to call mockReturnValueOnce on them.

Here's what I had to do:

In ../../../magic/__mocks__/index.js:

export const navigationEnabled = jest.fn();export const guidanceEnabled = jest.fn();

in my index.test.js file:

jest.mock('../../../magic/index');import { navigationEnabled, guidanceEnabled } from '../../../magic/index';import { functionThatReturnsValueOfNavigationEnabled } from 'moduleToTest';it('is able to mock', () => {  navigationEnabled.mockReturnValueOnce(true);  guidanceEnabled.mockReturnValueOnce(true);  expect(functionThatReturnsValueOfNavigationEnabled()).toBe(true);});