I am facing an issue with testing my NestJs Service. I have a method that performs 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 am trying to write a unit test for this method in order to cover all lines of code. Despite using the "nock" package to mock the http request, I am unable to improve the coverage result.
return throwError(error);
map(response => response.data);
These two lines remain uncovered.
Below is my test file:
describe('getEntries method', () => {
it('should perform a 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 an error if the request fails', () => {
nock('http://localhost:3000')
.get('/v1/entries')
.replyWithError('request failed');
service.getEntries().subscribe(res => {
expect(res).toBeUndefined();
}, err => {
expect(err).toBe('request failed');
})
});
});