'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?
Solution 1:[1]
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();
});
});
});
Or have the implementation within the file
In that case you'll have to test the both classes as that is your Unit
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |