我将如何测试一个订阅数据然后将其传递给另外两个函数的函数



我正在学习笑话,需要帮助了解如何在角度服务中测试特定功能。此函数不接受任何参数,并订阅一个get函数,然后将订阅中的数据传递给另外两个函数。我有模拟数据,但在编写测试时遇到了问题。

public export(): void {
this.getDataValues().subscribe((data) => {
this.exportDelays(data.delay);
this.exportCancels(data.cancels);
});
}

如有任何帮助,我们将不胜感激。谢谢。

您可以通过模拟getDataValues()函数的返回值来测试这一点。开玩笑地说,事情就这么简单。

describe('Service', () => {
let service: Service;

TestBed.configureTestingModule({
// imports, providers and declarations come here::
}).compileComponents();

beforeEach(() => {
service = TestBed.inject(Service);
});
it('export', () => {
const mockData = {
// create an object with the same type as your expected returnData
}
jest.spyOn(service, 'getDataValues').mockReturnValue(of(mockData));
jest.spyOn(service, 'exportDelays').mockImplementation();
jest.spyOn(service, 'exportCancels').mockImplementation();
service.export();

expect(service.getDataValues).toHaveBeenCalled();
expect(service.exportDelays).toHaveBeenCalled();
expect(service.exportCancels).toHaveBeenCalled();
}

请注意,您需要通过传递of(mockData)作为returnValue来返回一个发出mockData的observable。只有到那时,该函数才能订阅和触发其他服务方法。

最新更新