I have a mock module like this in my component test file
jest.mock('../../../magic/index', () => ({ navigationEnabled: () => true, guidanceEnabled: () => true }));
these functions will be called in render function of my component to hide and show some specific feature.
I want to take a snapshot on different combinations of the return value of those mock functions.
for suppose I have a test case like this
it('RowListItem should not render navigation and guidance options', () => { const wrapper = shallow( <RowListItem type="regularList" {...props} /> ); expect(enzymeToJson(wrapper)).toMatchSnapshot(); });
to run this test case I want to change the mock module functions return values to false
like this dynamically
jest.mock('../../../magic/index', () => ({ navigationEnabled: () => false, guidanceEnabled: () => false }));
because i am importing RowListItem
component already once so my mock module wont re import again. so it wont change. how can i solve this ?
To mock the return value of an imported function in Jest, you have to either call mockReturnValue or mockImplementation on a Jest mock function and then specify the return value. Which function mock function you should use depends on your situation.
To change mock implementation for a single test with Jest, we can call the mockImplementation method on the function we want to mock in our test. import { funcToMock } from './module'; jest. mock('./module'); beforeEach(() => { funcToMock.
To mock an exported constant in Jest and JavaScript, we can mock the imported modules with jest. mock . const mockTrue = { ENABLED: true }; const mockFalse = { ENABLED: false }; describe("allowThrough", () => { beforeEach(() => { jest. resetModules(); }); test("success", () => { jest.
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With