简体   繁体   中英

How to inject HttpClient in module mock

For testing I want to mock my dependency module NavigationService with a mock. In the mock class I need to make HTTP requests, so I need the HttpClient to be injected into my mock class. This is my 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?

You need to inject the HttpTestingController to use the mock of HttpClient . Here's how I do it (my ProductService makes an HTTP request in getProducts() ):

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);
  }));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM