In my Angular project, all the Rest services are defined like below, they have 4 signatures
public commandsGet(oem: string, countryCode?: string, observe?: 'body', reportProgress?: boolean): Observable<CommandGetResponse>;
public commandsGet(oem: string, countryCode?: string, observe?: 'response', reportProgress?: boolean): Observable<HttpResponse<CommandGetResponse>>;
public commandsGet(oem: string, countryCode?: string, observe?: 'events', reportProgress?: boolean): Observable<HttpEvent<CommandGetResponse>>;
public commandsGet(oem: string, countryCode?: string, observe: any = 'body', reportProgress = false): Observable<any> {
return this.httpClient.get<CommandGetResponse>(`${this.basePath}/${oem}/commands/`, params);
}
I'm writing some tests and trying to mock the service, but I'm getting error "Argument of type 'Observable' is not assignable to parameter of type 'Observable<HttpEvent>'"
it('should return expected commands', (done: DoneFn) => {
const mockResponse: CommandGetResponse = {
data: [
{ commandname: 'A' },
{ commandname: 'B' }],
count: 2
};
spyOn(commandService, 'commandsGet').and.returnValue(of(mockResponse) as Observable<CommandGetResponse>);
component.ngOnInit();
fixture.detectChanges();
expect(component.commands).toEqual(mockResponse.data);
});
I have also tried
spyOn(commandService, 'commandsGet').and.returnValue(of(mockResponse));
``
Then I'm getting "Argument of type 'Observable<CommandGetResponse>' is not assignable to parameter of type 'Observable<HttpEvent<CommandGetResponse>>'.
When I define:
const httpResponse = new HttpResponse({ body: mockResponse });
spyOn(commandService, 'commandsGet').and.returnValue(of(httpResponse));
I'm not getting any error but my tests fail as the object returned is not of type "CommandGetResponse"
Any help on this would be welcome.
Thanks
For testing files it does not really matter what types are set, so it's safe to use any
and just focus on testing and coverage.
it('should return expected commands', (done: DoneFn) => {
const mockResponse: any = { // <- changed here!
data: [
{ commandname: 'A' },
{ commandname: 'B' }],
count: 2
};
spyOn<any>(commandService, 'commandsGet').and.returnValue(of(mockResponse) as any);// <- changed here!
component.ngOnInit();
fixture.detectChanges();
expect(component.commands).toEqual(mockResponse.data);
});