如何在模块mock中注入HttpClient

时间:2018-02-17 16:21:27

标签: angular unit-testing

为了测试,我想用mock模拟我的依赖模块NavigationService。在mock类中,我需要发出HTTP请求,所以我需要将HttpClient注入到我的mock类中。这是我的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注入模拟类?

1 个答案:

答案 0 :(得分:-1)

您需要注入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);
  }));