Ach*_*yut 5 node.js rxjs typescript jestjs nestjs
我对 NestJS + Typescript + RxJs 技术堆栈相当陌生。我正在尝试使用 Jest 为我的功能之一编写单元测试用例,但不确定是否正确执行。
组件.service.ts
public fetchComponents(queryParams) {
const url = this.prepareUrl(queryParams);
const data$ = this.httpService.get(url);
return data$
.pipe(map(({ data }) => data));
}
Run Code Online (Sandbox Code Playgroud)
组件.服务.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');
}
);
});
});
Run Code Online (Sandbox Code Playgroud)
您能否提供有关我应该如何测试此功能的建议和指示。也不使用库,就像marbel-rx
我不确定我是否正确测试它一样。还有什么我应该测试的吗?
由于Observables是异步的,您必须添加异步done参数并done()在expect最后执行的之后调用。否则, jest 将在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
}
);
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3662 次 |
| 最近记录: |