Подтвердить что ты не робот

Угловой 5 сервис, не прошедший модульные тесты с помощью (NullInjectorError: Нет провайдера для HttpClient!)

Я продолжаю получать следующие ошибки при выполнении модульных тестов

Error: StaticInjectorError(DynamicTestModule)[ApiService -> HttpClient]: 
      StaticInjectorError(Platform: core)[ApiService -> HttpClient]: 
        NullInjectorError: No provider for HttpClient!

api.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class ApiService {

  constructor(private http: HttpClient) { }
  url = './assets/data.json';

  get() {
    return this.http.get(this.url);
  }
}

api.service.spec.ts

import { TestBed, inject } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';

import { ApiService } from './api.service';

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

  it('should get users', inject([HttpTestingController, ApiService],
      (httpMock: HttpTestingController, apiService: ApiService) => {
        expect(apiService).toBeTruthy();
      }
    )
  );
});

Я не понимаю, что происходит не так, поскольку я включил HttpClient в api.service.ts, служба работает в браузере.

Это напрямую вызывается в компоненте MapComponent, который вызывается внутри HomeComponent.

Chrome 63.0.3239 (Mac OS X 10.13.3) HomeComponent expect opened to be false FAILED
    Error: StaticInjectorError(DynamicTestModule)[ApiService -> HttpClient]: 
      StaticInjectorError(Platform: core)[ApiService -> HttpClient]: 
        NullInjectorError: No provider for HttpClient!
4b9b3361

Ответ 1

Причина "NullInjectorError: No provider for HttpClient!" неразрешенные зависимости. В этом случае отсутствие HttpClientModule.

В ваш файл .service.spec.ts добавьте

  imports: [
        HttpClientTestingModule,
    ],

Вы можете заметить, что я написал HttpClientTestingModule вместо HttpClientModule. Причина в том, что мы не хотим отправлять реальные http-запросы, а используем Mock API тестовой среды.

Ответ 2

Попробуйте обернуть inject в async, как async ниже:

import { TestBed, async, inject } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { ApiService } from './api.service';

describe('ApiService', () => {
    beforeEach(() => {
      ...
    });    

  it('should create', async(inject([HttpTestingController, ApiService],
    (httpClient: HttpTestingController, apiService: ApiService) => {
      expect(apiService).toBeTruthy();
  })));

});

Не забудьте импортировать async из @angular/core/testing.

У меня был хороший успех. Это единственное отличие от ваших модульных тестов и моих, где я использую HttpClientTestingModule.

Ответ 3

просто добавьте это так,

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [
        HttpClientModule,
      ],
    }).compileComponents();
  });