score:172

Accepted answer

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)
//or
navigationenabled.mockreturnvalueonce(true);

and in the next test

navigationenabled.mockimplementation(()=> false)
//or
navigationenabled.mockreturnvalueonce(false);

score:9

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);
});

score:36

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


Related Query

More Query from same tag