具有多重签名的 Angular 模拟服务

问题描述 投票:0回答:1

在我的 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’类型的参数”

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”类型

欢迎对此提供任何帮助。

谢谢

angular testing jasmine karma-runner spyon
1个回答
0
投票

对于测试文件,设置什么类型并不重要,因此可以安全使用

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);
    });
© www.soinside.com 2019 - 2024. All rights reserved.