Angular - Override/Mock methods get, post, put, delete from HTTP for testing

Viewed 1394

I'm trying to mock the Http class so I could inject it on a service that I want to test.

Usually, I create a mock class that extends the class that will be override. For this case, I did something like this:

export class MockHttp extends Http {
    constructor(){super(undefined, undefined);}
    get(url: string, options?: RequestOptionsArgs): Observable<Response> {
        return new Observable((observer) => {
            observer.next(undefined);
            observer.complete();
        });
    }
}

But the intelisense of vs code give me the following error, on the method get:

Property 'get' in type 'MockAppHttpClientService' is not assignable to the same property in base type 'Http'.

Any one knows how to solve this?

1 Answers

You don't have to write your own mock as it is not that trivial task. Angluar already provides utilities to mock http client for unit testing. It is described in sufficient details in official documentation

https://angular.io/guide/testing#testing-http-services

In short, use HttpClientTestingModule

Related