我对NestJS + Typescript + RxJs技术堆栈还很陌生。我正在尝试使用Jest为我的函数之一编写单元测试用例,但不确定是否正确执行了。
component.service.ts
public fetchComponents(queryParams) {
const url = this.prepareUrl(queryParams);
const data$ = this.httpService.get(url);
return data$
.pipe(map(({ data }) => data));
}
component.sevice.spec.ts
测试用例可以通过并通过
describe('fetchComponents', () => {
const query = {
limit: 10,
offset: 0
};
const result: AxiosResponse = {
data: 'Components',
status: 200,
statusText: 'OK',
headers: {},
config: {}
};
it('should return Dummy Data when called successfully', () => {
componentService.prepareUrl = jest.fn();
jest.spyOn(httpService, 'get').mockImplementation(() => of(result));
componentService.fetchComponents(market, query)
.subscribe(
(res) => {
expect(res).toEqual('Components');
}
);
});
});
能否请您提供一些有关我应该如何正确测试此功能的建议和指示。也无需使用像marbel-rx
这样的库
我不确定测试是否正确。还有其他我应该测试的东西吗?
答案 0 :(得分:0)
由于Observables
是异步的,因此必须调用添加异步done
参数,并在最后执行的done()
之后调用expect
。否则,玩笑将在调用subscribe()
之后完成测试运行,而无需等待subscribe
的回调的异步执行的执行。尝试使测试失败,例如通过期望'Komponents'
。测试不会失败。
此外,我建议尽可能使用mockImplementationOnce
而不是mockImplementation
,以避免在以后的调用中隐式重用模拟行为并因此创建隐式依赖项。
it('should return Dummy Data when called successfully', done => {
// Add done parameter ^^^^
componentService.prepareUrl = jest.fn();
jest.spyOn(httpService, 'get').mockImplementationOnce(() => of(result));
// Prefer mockImplementationOnce ^^^^
componentService.fetchComponents(market, query)
.subscribe(
(res) => {
expect(res).toEqual('Components');
done();
// ^^^^^^ Call done() when test is finished
}
);
});