How to use jest to mock out a private variable - reactjs

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

Related

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 partially mock a custom react hook with Jest?

I would like to mock some of my custom React hook return value with Jest.
Here is an example of what i'm trying to do :
export default function useSongPlayer() {
const playSongA = () => {...}
const playSongB = () => {...}
const playSongC = () => {...}
return {
playSongA,
playSongB,
playSongC,
}
}
Now in my test, I would like to mock only playSongA and keep the other functions real implementations. I tried several approachs, including someting with jest.requireActual('hooks/useSongPlayer') but it seems that playSongA is successfully mocked while the others are just undefined.
With something like this, i'm pretty sure to achieve what i want
export function playSongA() {...}
export function playSongB() {...}
export function playSongC() {...}
The problem seems to be the module I try to mock is a function, and I want to partially mock the result of this function.
This is possible if you create a mock that returns the original, but also intercepts the function calls and replaces one of the values.
You can do this without a Proxy, but I choose to demonstrate that as it's the most complete method to intercept any use of the actual hook.
hooks/__mocks__/useSongPlayer.js
// Get the actual hook
const useSongPlayer = jest.requireActual('hooks/useSongPlayer');
// Proxy the original hook so everything passes through except our mocked function call
const proxiedUseSongPlayer = new Proxy(useSongPlayer, {
apply(target, thisArg, argumentsList) {
const realResult = Reflect.apply(target, thisArg, argumentsList);
return {
// Return the result of the real function
...realResult,
// Override a single function with a mocked version
playSongA: jest.fn(),
};
}
});
export default proxiedUseSongPlayer;

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

React and Jest: How to mock implementation of member function

I'm doing some api fetching in my component. When doing unit testing, I'd like to mock the implementation of certain member functions:
//component.js
class Foo extends Component {
prepareData() {
getSthFromApi().then(getMoreFromApi).then(val=>this.setState({val}));
}
componentDidMount() {
this.prepareData();
}
}
//test.js
//What should this be?
Foo.prepareData = jest.fn().mockImplementation(() => {
this.setState({val:1});
})
const comp = shallow(<Foo />);
How should I do it?
You shouldn't mock your member function, instead you can mock getSthFromApi function and test both componentDidmount and prepareData together.
import { getSthFromApi } from "some-module";
jest.mock("some-module");
// in your test
getSthFromApi.resolves(1);
// here you can expect val to be 1 in your state.
The problem with this code is that Foo.prepareData is static method, while prepareData is instance method.
Since prepareData is prototype method, it can be mocked on class prototype; this is one of the reasons why prototype methods are preferable:
jest
.spyOn(Foo.prototype, 'prepareData')
.mockImplementation(function () {
this.setState({val:1});
});
Notice that mockImplementation should be provided with regular function because it doesn't need lexical this.

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

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

Resources