簡體   English   中英

如何在模塊模擬中注入 HttpClient

[英]How to inject HttpClient in module mock

為了測試,我想用一個模擬來模擬我的依賴模塊NavigationService 在模擬類中,我需要發出 HTTP 請求,因此我需要將HttpClient注入到我的模擬類中。 這是我的beforeEach

beforeEach (() => {
  TestBed.configureTestingModule ({
    imports: [HttpClient, RouterTestingModule],
    providers: [
      {
        provide: NavigationService, useClass: class {
          constructor (httpClient: HttpClient) {
          }
          method1() {
            return this.httpClient.get('/some-url');
          }
        },
      },
    ]
  });
});

但這不起作用,它在每次測試時都會出錯:

Error: Can't resolve all parameters for class_1: (?).

那么如何正確地將HttpClient注入到模擬類中呢?

您需要注入HttpTestingController以使用HttpClient的模擬。 這是我的操作方法(我的ProductServicegetProducts()發出 HTTP 請求):

describe('ProductService', () => {
  let productService: ProductService;
  let httpMock: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      providers: [ProductService]
    });

    productService = TestBed.get(ProductService);
    httpMock = TestBed.get(HttpTestingController);
  });

  it('should successfully get products', async(() => {
    const productData: Product[] = [{ "id":"0", "title": "First Product", "price": 24.99 }];
    productService.getProducts()
      .subscribe(res => expect(res).toEqual(productData));

    // Emit the data to the subscriber
    let productsRequest = httpMock.expectOne('/data/products.json');
    productsRequest.flush(productData);
  }));

暫無
暫無

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

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