В моем проекте 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».
Любая помощь в этом вопросе будет приветствоваться.
Спасибо
Для тестирования файлов не имеет особого значения, какие типы установлены, поэтому можно безопасно использовать any
и просто сосредоточиться на тестировании и покрытии.
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);
});
спасибо, это сработало. Я сделал();" на тесте...