Resetting the value of a mocked module in a Jest unit test - reactjs

I'm trying to mock out methods in an imported module while testing a separate module. I'm able to successfully mock the imported module with ES2015 import syntax, but the mock stays consistent throughout the entire test and there are instances where I'd like to change the mock.
My files look like this
// ModuleA
import ModuleB from 'ModuleB'
// ... code
// TestCase
import ModuleA from 'ModuleA'
import ModuleB from 'ModuleB'
jest.mock('ModuleB', () => {
return {
value: true
}
}
describe('ModuleA', () => {
it('returns true', () => {
// This test expects ModuleB.value to return true
});
it('returns false', () => {
// This doesn't work
ModuleB.value = jest.fn(() => false)
// This doesn't work either
jest.mock('ModuleB', () => {
return {
value: false
}
});
// This test expects ModuleB.value to return false in order to pass
});
});
I essentailly need to separate mocks for ModuleB. In the past, I've been able to simply use var ModuleB = require('ModuleB'); instead of import and then call ModuleB.someMethodName = jest.fn() whenever needed. I'd like to use only ES2015 for these tests though, and using the pattern I just mentioned gives me a ModuleB is read-only error.

Use the requireActual method:
To ensure that a manual mock and its real implementation stay in sync, it might be useful to require the real module using require.requireActual(moduleName) in your manual mock and amending it with mock functions before exporting it.
For example:
const RealModule = require.requireActual('Form');
const MyModule = {
RealThing: RealModule.RealThing,
…add some mocks
};
References
jest.js Issue #1557: How to mock just the React components from a module exporting many things
jest.js Issue #1273: require.requireActual not returning the actual mock
Troubleshooting · Jest

Related

How to override a global jest mock in a specific test?

I am using #testing-library/react v13.4.0 with jest v29.
I am mocking the services/ledger.ts module with services/__mocks__/ledger.ts. I'll focus on one method in this file, which is defined as follows:
// services/__mocks__/ledger.ts
export const getAccounts = jest.fn(() => mockGetAccounts);
I have a setupTests.tsx that runs as setupFilesAfterEnv with the following code:
// setupTests.tsx
jest.mock('services/ledger');
This works nicely as a global mock, but for certain tests I want to override this mock. In a test file, I have the following code:
// Account.test.tsx
import { mockGbpAccount } from 'testing';
import { getAccounts } from 'services/ledger';
...
describe('components: Account', () => {
// some other tests that don't have any mocks
it('should disable GBP withdraw button if user has a balance of 0', async () => {
(getAccounts as jest.Mock).mockImplementation(() => ({
account: [
mockBtcAccount,
{ ...mockGbpAccount, balance: { formatted: '0' } },
],
}));
await renderWithProviders(<Account accountId={mockGbpAccount.id} />);
await waitFor(() => {
expect(screen.getByTestId('withdraw-cta')).toBeDisabled();
});
});
});
The resulting balance is not 0 as expected, but the default balance I set in the global mock.
Weirdly, when I run this test alone with -t, and not the entire suite, it passes. The specific test also passes when it's the first test in the suite, but not the second+ test.
I have tried different ways of mocking globally, and mocking in the specific suite, but it always uses the global mock value.
How can I override a global mock for specific tests?

Is it possible to mock functions outside of the test file for multiple tests to use?

Thanks in advance
Issue
I have some functions that need to be mocked in every test file. However, only in some of those files, do I actually care to evaluate or test those mock functions.
For example, let's say, that when my app renders, it immediately fetches some data In A.test.tsx I want to mock that fetch and verify that it was called.
But, in B.test.tsx, I still need to mock that fetch, but I don't care to verify that it was called.
Goal
I would like the setup to look something like this:
setup.ts
import * as SomeAPI from 'api';
const setup = () => {
jest.spyOn(SomeAPI, 'fetchData');
return { SomeAPI };
};
export default setup;
A.test.tsx
const { SomeAPI } = setup();
beforeEach(() => {
jest.clearAllMocks();
});
test('data should be fetched when app renders', async () => {
RenderWithProviders(<App />);
expect(SomeAPI.fetchData).toHaveBeenCalled();
});
B.test.tsx
setup(); // Don't destructure because I don't care to test the mock
beforeEach(() => {
jest.clearAllMocks();
});
test('test some other stuff', async () => {
// In this case, the fetchData still needs to be mocked<br>
// because the rest of the app depends on it
RenderWithProviders(<App />);
expect(someElement).toBeInTheDocument();
});
My Current Problem
My problem is that while I'm trying to attempt this way of returning mocked functions... If that mocked function is used more than once in the same test file, the jest.clearAllMocks() seems not to have an effect. I assume because the setup is happening outside of the test?
Is this possible to setup mocks outside of the test and only destructure them when needed?

How to use jest to mock out a private variable

I am trying to write a unit test for a function like this:
export class newClass {
private service: ServiceToMock;
constructor () {
this.service = new ServiceToMock()
}
callToTest () {
this.service.externalCall().then(()=> {
//Code to test
})
}
}
In order to test this piece of code I need to mock out service because it calls a function outside of the class but the problem is it's private.
How exactly do I mock out a private variable with jest? The class creates its own instance of it so is it even possible to mock out?
In your implementation you either import the service
implementation.js
import ServiceToMock from './serviceToMock.js';
implementation.spec.js
// import the already mocked service
import ServiceToMock from './serviceToMock.js';
import newClass from './implementation';
// auto-mock the service
jest.mock('./serviceToMock.js');
describe('newClass', () => {
describe('somMethod', () => {
beforeAll(() => {
// it is recommended to make sure
// the previous calls are cleared
// before writing assertions
ServiceToMock.prototype.externalCall.mockClear()
// jest's auto-mocking will create jest.fn()
// for each of the service's methods
// and you will be able to use methods like .mockResolvedValue
// to modify the mock behavior
ServiceToMock.prototype.externalCall.mockResolvedValue(data);
// call your method
(new newClass).someMethod();
});
it('should call ServiceToMock.externalCall', () => {
// and you can write assertions for the mocked methods
expect(ServiceToMock.prototype.externalCall).toHaveBeenCalledWith();
});
});
});
working example without Types
Or have the implementation within the file
In that case you'll have to test the both classes as that is your Unit

how to use jest to mock method of react class

I want to mock method of react class so that the unit test can run follow the mock function.
React: 16.8.6
jest: 24.8.0
Overview.js
import React from 'react';
export default class Overview extends Component{
test1(){
return {
// fetch api
}
}
test2(){
const result = this.test1();
// do other thing
return result
}
}
overview.test.js
import Overview from './index';
import { mount } from 'enzyme';
import React from 'react';
describe('test Overview',()=>{
const mockResult = {test1:'test1'};
console.info(Overview.prototype) // {}
Overview.prototype.test1=jest.fn(()=>{
return mockResult
});
it('func test2',()=>{
const wrapper = mount(<Overview/>);
const {test2} = wrapper.instance();
expect(mockResult).toEqual(test2())
})
})
Expect: run success
Actual result: run fail, because Overview.prototype cannot override or mock test1 function.
When I tried to print 'Overview.prototype', I get {}. That let me so confuse.
How to mock test1 function and why Overview cannot be overrode?
Please help me.
Try to do this:
it('func test2',()=>{
const wrapper = mount(<Overview/>);
wrapper.instance().test1 = jest.fn(() => mockResult);
expect(wrapper.instance().test2()).toEqual(mockResult);
})
There are plenty of reason to choose different approach than mocking internal methods and checking against internal methods:
it's hard and even impossible somtimes(once method under mock change state or even access variable by closure)
you stick to implementation details so even smallest refactoring(renaming internal method or property name in state) make you update tons of tests
it makes you even more confident in your component(say what if test1() stopped to call fetch()? but your tests with mocking it would not even know that component is broken)
Here is different approach: mock only external API and communicate only through public interface(for React component it's props and render() result you may access with Enzyme's methods like .find(), .filter(), .text() etc)
There are several packages that mocks global fetch() like fetch-mock but you actually may mock it on your own(don't forget to mock it with Promise not plain data):
global.fetch = jest.fn();
beforeEach(() => {
// important for mocks to keep them fresh on each test case run
global.fetch.mockClear();
});
it('renders error if fetching failed', async () => {
global.fetch.mockReturnValue(Promise.reject({}));
const wrapper = shallow(<Overview />);
wrapper.find('.some-button-to-click').props().onClick();
await Promise.resolve(); // let's wait till mocked fetch() is resolved
expect(wrapper.find('.error').text()).toEqual('Unable to load users. Try later.');
});

Jest - Mock Nested Function

I am writing a JEST/Enzyme test case for module.
One of the function I am testing in my component is about saving an xml file. Which in turn calls a library function fileDownload from 'react-file-download'
const saveContentToXML = () => {
if(this.props.message && this.props.message.details){
fileDownload(this.props.message.details, this.props.message.title);
}
}
When I wrote test case, it calls saveContentToXML and in turn calls fileDownload. This results in exception.
TypeError: window.URL.createObjectURL is not a function
My test case looks like
test('Save Content as XML Test', () =>{
const component = shallow(<Message details={details} />);
component.instance().saveContentToXML();
});
How do I test this function?
You should mock react-file-download and then assert that it is being called
// Default mock will just make fileDownload a jest mock function
jest.mock('react-file-download')
import fileDownload from 'react-file-download'
test('Save Content as XML Test', () =>{
const component = shallow(<Message details={details} />);
component.instance().saveContentToXML();
expect(fileDownload).toHaveBeenCalledWith('details', 'title');
fileDownload.mockClear() // resets the mock function so the call is not used in assertions for other tests
});
The jest documentation on mock functions is a good resource to refer to: https://facebook.github.io/jest/docs/mock-functions.html

Resources