I am having trouble to test my NestJs Service. I wrote a method, which does a GET http request:
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)
);
}
I want to write a unit test for this method. This unit test should cover all lines of this method. I tried to use "nock" package to mock this http request, but no matter how i try the coverage result is always the same.
return throwError(error);
map(response => response.data);
This two lines were uncovered.
Here my test file:
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');
})
});
});