【发布时间】:2020-08-13 10:45:20
【问题描述】:
我无法测试我的 NestJs 服务。我写了一个方法,它执行 GET http 请求:
getEntries(): Observable<Entries[]> {
Logger.log(`requesting GET: ${this.apiHost}${HREF.entries}`);
return this.http.get(`${this.apiHost}${HREF.entries}`).pipe(
catchError((error) => {
return throwError(error);
}),
map(response => response.data)
);
}
我想为此方法编写一个单元测试。此单元测试应涵盖此方法的所有行。 我尝试使用“nock”包来模拟这个http请求,但无论我如何尝试覆盖结果总是一样的。
return throwError(error);
map(response => response.data);
这两行被发现了。
这是我的测试文件:
describe('getEntries method', () => {
it('should do get request and return entries', () => {
nock('http://localhost:3000')
.get('/v1/entries')
.reply(200, {
data: require('../mocks/entries.json')
});
try {
const result = service.getEntries();
result.subscribe(res => {
expect(res).toEqual(require('../mocks/entries.json'));
});
} catch (e) {
expect(e).toBeUndefined();
}
});
it('should return error if request failed', () => {
nock('http://localhost:3000')
.get('/v1/entries')
.replyWithError('request failed');
service.getEntries().subscribe(res => {
expect(res).toBeUndefined();
}, err => {
expect(err).toBe('request failed');
})
});
});
【问题讨论】:
标签: typescript unit-testing jestjs nestjs