簡體   English   中英

如何使用嚴格的 TypeScript 進行模擬

[英]How to mock with strict TypeScript

例如:

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 提供了一個很好的包來測試 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM