我正在尝试为这样的功能编写单元测试:
export class newClass {
private service: ServiceToMock;
constructor () {
this.service = new ServiceToMock()
}
callToTest () {
this.service.externalCall().then(()=> {
//Code to test
})
}
}
为了测试这段代码,我需要模拟服务,因为它调用了类外部的函数,但是问题是它是私有的。
我该如何精确地嘲笑一个私有变量?该类将创建自己的实例,因此甚至有可能模拟出来吗?
答案 0 :(得分:0)
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();
});
});
});
在这种情况下,您必须测试两个类,因为这是您的单元