简体   繁体   English

如何在模块模拟中注入 HttpClient

[英]How to inject HttpClient in module mock

For testing I want to mock my dependency module NavigationService with a mock.为了测试,我想用一个模拟来模拟我的依赖模块NavigationService In the mock class I need to make HTTP requests, so I need the HttpClient to be injected into my mock class.在模拟类中,我需要发出 HTTP 请求,因此我需要将HttpClient注入到我的模拟类中。 This is my beforeEach :这是我的beforeEach

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

But that does not work, it gives an error on every test:但这不起作用,它在每次测试时都会出错:

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

So how do I correctly inject HttpClient into the mock class?那么如何正确地将HttpClient注入到模拟类中呢?

You need to inject the HttpTestingController to use the mock of HttpClient .您需要注入HttpTestingController以使用HttpClient的模拟。 Here's how I do it (my ProductService makes an HTTP request in getProducts() ):这是我的操作方法(我的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