角服务测试在函数参数中返回的承诺会返回无效

问题描述

根据https://angular.io/guide/testing-services#testing-http-services,我编写了以下service.spec(角度8):

import { HttpClientTestingModule } from '@angular/common/http/testing';
import { inject,Testbed } from '@angular/core/testing';

import { MyService } from "../../services/my.service";

describe('MyService',() => {

    let httpClientSpy: { get: jasmine.Spy; post: jasmine.Spy };

    let service: MyService;

    beforeEach(() => {
        Testbed.configureTestingModule({
            imports: [HttpClientTestingModule],providers: [MyService]
        }); // this I need for another test
        httpClientSpy = jasmine.createSpyObj('HttpClient',['get','post']);
        service = new MyService(httpClientSpy as any);
    });

    it('checkAccess returns true',() => {
        httpClientSpy.get.and.returnValue({ subscribe: () => true });

        service
            .checkAccess(1234)
            .subscribe((value: boolean) => // ESLint marks this...
                expect(value).toBeTruthy(),// ... and this ...
                fail                         // ... as a problem
            );
    });
}

服务方法

public checkAccess(id: number): Observable<boolean> {
    return this.http.get<any>(`${this.apiUrlPart}/${id}/access`,{
        params: new InterceptorHttpParams({ showLoader: true },{})
    });
}

所有测试(我为某些服务的方法编写了一些具有相同原理的测试)都成功通过,应用程序构建也成功。

但是,我的ESLint提出了规范的.subscribe行(第一个代码片段)的问题“在函数参数中返回了Promise,期望返回空值”。 我读了https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-misused-promises.md#options,还用Google搜索了,发现了一些对我没有帮助的建议。例如:

httpClientSpy.get.and.returnValue(asyncData(true)); // with asyncData helper from ng docs - see the link above
httpClientSpy.get.and.returnValue(of(true));

在那之后,我终于想问一问,也许这样的构造对于测试是可以的,因此我应该只对spec文件禁用此规则(或配置类似https://github.com/typescript-eslint/typescript-eslint/blob/master/packages/eslint-plugin/docs/rules/no-misused-promises.md#options的规则)? 如果确实有错误应该解决,我该怎么办?

谢谢

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)