Sigo recibiendo los siguientes errores cuando ejecuto pruebas unitarias
Error: StaticInjectorError(DynamicTestModule)[ApiService -> HttpClient]: StaticInjectorError(Platform: core)[ApiService -> HttpClient]: NullInjectorError: No provider for HttpClient!api.servicio.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.servicio.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(); } ) ); });No entiendo qué está fallando, ya que incluí HttpClient en api.service.ts, el servicio funciona en el navegador.
Esto se llama directamente en un componente llamado MapComponent, y eso se llama dentro de 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!El motivo de "NullInjectorError: No provider for HttpClient!" son dependencias no resueltas. En este caso, la falta de un HttpClientModule .
En su archivo .service.spec.ts agregue
imports: [ HttpClientTestingModule, ], Puede notar que escribí HttpClientTestingModule en lugar de HttpClientModule . La razón es que no queremos enviar solicitudes http reales, sino usar una API simulada del marco de prueba.
simplemente añádelo así,
beforeEach(() => { TestBed.configureTestingModule({ imports: [ HttpClientModule, ], }).compileComponents(); });Intente envolver su inject en un async , como a continuación:
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(); }))); }); No olvides importar async desde @angular/core/testing .
He tenido buen éxito con esto. Es lo único diferente de sus pruebas unitarias y las mías donde uso HttpClientTestingModule .