在我的Angular项目中,所有的Rest服务都定义如下,它们有4个签名
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);
}
我正在编写一些测试并试图模拟该服务,但我收到错误消息:"类型为‘Observable’的参数不可赋值给类型为‘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);
});
我也试过了
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>>'.
当我定义:
const httpResponse = new HttpResponse({ body: mockResponse });
spyOn(commandService, 'commandsGet').and.returnValue(of(httpResponse));
我没有收到任何错误,但我的测试失败,因为返回的对象不是"CommandGetResponse"类型
这方面的任何帮助都将是受欢迎的.
谢谢