【问题标题】:How to mock with strict TypeScript如何使用严格的 TypeScript 进行模拟
【发布时间】:2021-09-07 18:11:05
【问题描述】:

例如:

let mockhttp; // 1

beforeEach(() => {
    mockhttp = { //3
        get: jest.fn()
    };

    mockhttp.get.mockReturnValue(of(...)); //4
});

it('should fetch', async () => {
    const service = new MyService(mockhttp as any as HttpClient); //2
});

这将在 1 和 2 上产生以下错误。

Variable 'mockhttp' implicitly has type 'any' in some locations where its type cannot be determined.

let mockhttp; 更改为let mockhttp: HttpClient;

给出 3:

Type '{ get: Mock ; }' is missing the following properties from type 'HttpClient': handler, request, delete, head, and 5 more.

4:

TS2339: Property 'mockReturnValue' does not exist on type '{ (url: string, options: { headers?: HttpHeaders | { [header: string]: string | string[]; }; context?: HttpContext; observe?: "body"; params?: HttpParams | { [param: string]: string | number | boolean | readonly (string | ... 1 more ... | boolean)[]; }; reportProgress?: boolean; responseType: "arraybuffer"; withCred...'

有没有办法在不到处添加//@ts-ignore 的情况下解决这个问题?

注意:这个问题不是关于测试 httpclient 或任何相关的。它仅用于演示目的。它可以是任何其他服务或组件。

【问题讨论】:

标签: angular typescript jestjs


【解决方案1】:

Angular 提供了一个很好的包来测试 HTTP 通信。

describe('AppComponent', () => {
  let component: AppComponent;
  let fixture: ComponentFixture<AppComponent>;
  let httpMock: HttpTestingController;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      declarations: [AppComponent]
    })
      .compileComponents();

    httpMock = TestBed.inject(HttpTestingController);
  }));

这是一篇带有示例的好文章:Testing Angular HTTP Communication

【讨论】:

  • 这个问题不是关于测试 HttpClient
  • 对不起,我并没有限制自己停止轮子的改造(:
  • @RobinDijkhof HttpClientTestingModule 不是关于测试 HttpClient,而是测试 使用 它的东西,这就是你似乎正在做的事情。见angular.io/guide/http#testing-http-requests
猜你喜欢
  • 2011-12-21
  • 2014-07-02
  • 2020-08-20
  • 2019-07-08
  • 2011-03-09
  • 2014-08-29
  • 2021-01-13
  • 2013-10-08
相关资源
最近更新 更多