ng测试期间的StaticInjectorError

时间:2018-04-26 11:10:47

标签: angular

我在运行测试时遇到此错误我的app模块似乎没问题我在我的模块和servive测试中都有导入我有提供者[服务]我不知道为什么所有测试都失败以下是其中一个失败测试任何一个请建议谢谢

   Error: StaticInjectorError(DynamicTestModule)[OrderService -> HttpClient]: 
              StaticInjectorError(Platform: core)[OrderService -> HttpClient]: 
                NullInjectorError: No provider for HttpClient!
                at _NullInjector.webpackJsonp../node_modules/@angular 
            Error: StaticInjectorError(DynamicTestModule)[OrderService -> HttpClient]: 
          StaticInjectorError(Platform: core)[OrderService -> HttpClient]: 
            NullInjectorError: No provider for HttpClient!

这是服务类

import  { Injectable } from '@angular/core';
 import {HttpClient, HttpErrorResponse, HttpHeaders, HttpResponse} from "@angular/common/http"; 

@Injectable()
export class OrderService {

  baseUrl : string = 'http://localhost:8088/orders';

  filterUrl: string = 'http://localhost:8088/orders?start=?&end=?';

  private order: Order;
  private headers = new HttpHeaders({'Content-Type': 'application/json'});


  constructor(private http: HttpClient) { }

  getOrders(From: Date, To: Date): Observable<Order[]> {
    return this.http.get(this.baseUrl + '?start=' + From + '&end=' + To)
      .pipe(map(this.extractData),
        tap(data => console.log(JSON.stringify(data))),
        catchError(this.handleError)
      );
  }

  createOrder(order: Order): Observable<number> {
    return this.http.post(this.baseUrl, JSON.stringify(order), {headers: this.headers})
      .pipe(map(this.extractData),
        catchError(this.handleError));
  }

我是app module.ts我有

imports: [
    NgbModule.forRoot(),
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    HttpClientModule,
    ReactiveFormsModule

  ],
      providers: [OrderService,TruckService],
export class AppModule {
   constructor(router: Router) {
     console.log('Routes: ', JSON.stringify(router.config, undefined, 2));
    }
 }

这是测试

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

  afterEach(inject([HttpTestingController], (httpClient: HttpTestingController) => {
    httpClient.verify();
  }));


  it(`should create`, async(inject([TruckService, HttpTestingController],
    (service: TruckService, httpClient: HttpTestingController) => {
      expect(service).toBeTruthy();
    })));

1 个答案:

答案 0 :(得分:2)

为了测试使用HttpClient的服务,您将不得不包含来自Angular的测试模块和控制器。

这包括用于后端配置的HttpClientTestingModule和用于模拟和刷新请求的HttpTestingController

这可能对你有用:

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

describe('TruckService', () => {

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

afterEach(inject([HttpTestingController], (httpClient: HttpTestingController) => {
    httpClient.verify();
}));

it(`should create`, async(inject([TruckService, HttpTestingController],
    (service: TruckService, httpClient: HttpTestingController) => {
    expect(service).toBeTruthy();
})));
});

有关在Angular HttpClient中测试HTTP请求的详细信息,请转到here。以下是HttpClientTestingModuleHttpTestingController上的API详细信息。