在Angular 10中使用ng test进行测试时如何克服业力中的NullInjector错误

问题描述

在Angular应用程序中,我已经成功创建了一个网页。它执行得很好。

但是当我使用 ng测试进行测试时,它显示了业障方面的一些错误。喜欢

Spec List | Failures
AdminComponent > should create
NullInjectorError: R3InjectorError(DynamicTestModule)[DashboardService -> HttpClient -> HttpClient]: 
  NullInjectorError: No provider for HttpClient!
error properties: Object({ ngTempTokenPath: null,ngTokenPath: [ 'DashboardService','HttpClient','HttpClient' ] })
NullInjectorError: R3InjectorError(DynamicTestModule)[DashboardService -> HttpClient -> HttpClient]: 
  NullInjectorError: No provider for HttpClient!
    at NullInjector.get (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:1013:1)
    at R3Injector.get (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:11122:1)
    at R3Injector.get (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:11122:1)
    at injectInjectorOnly (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:899:1)
    at ɵɵinject (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:903:1)
    at Object.DashboardService_Factory [as factory] (ng:///DashboardService/ɵfac.js:5:44)
    at R3Injector.hydrate (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:11289:1)
    at R3Injector.get (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:11111:1)
    at NgModuleRef$1.get (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:24243:1)
    at Object.get (http://localhost:9876/_karma_webpack_/node_modules/@angular/core/fesm2015/core.js:22142:1)
Expected undefined to be truthy.
Error: Expected undefined to be truthy.
    at <Jasmine>

admin.component.ts

import { Component,OnInit,ViewChild } from '@angular/core';
import { HttpClient,HttpHeaders } from '@angular/common/http';
import { DashboardService } from '../dashboard.service';
import { environment } from 'src/environments/environment';

@Component({
  selector: 'app-admin',templateUrl: './admin.component.html',styleUrls: ['./admin.component.css']
})
export class AdminComponent implements OnInit {

  constructor(private ds:DashboardService,private http:HttpClient) { }
 public superuser:any;
  public userlist:any;
  public last_login:any;
  public logi_ip:any;
  public usersloginstatus:any;
  ngOnInit() {
    this.ds.userslastlogin()
      .subscribe((usersloginstatus) => {
        this.usersloginstatus = usersloginstatus;

        console.log('obj4',usersloginstatus);
        this.superuser = this.usersloginstatus.superuser;
        this.userlist = this.usersloginstatus.users;
        console.log('obj5',this.superuser);
        console.log('obj6',this.userlist);
      },err => {
          console.log("Error",err)
        }
      );
}
  createActivity(){

    var userURLconf = '';
    let userprof = JSON.parse(localStorage.getItem('profile'));
    if (userprof.usertype == 'Admin') {
      userURLconf = '/api/activity/adminhistory';
    } else if (userprof.usertype == 'Super User') {
      userURLconf = '/api/activity/superuserhistory';
    } else {
      userURLconf = '/api/activity/userhistory';
    }
  
  
    let httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json','Authorization': 'Token ' + localStorage.getItem('token')
      })
    };
    this.http.post(environment.apiUrl + userURLconf,JSON.stringify({ location: localStorage.getItem('cityname'),action_status: 1}),httpOptions).subscribe(
      (dataforlogin) => {
        console.log(dataforlogin);
  
      },err => {
        console.log("Error",err)
      }
  
    );
  
  }
  }

dashboard.service.ts

import { Injectable } from '@angular/core';
import { HttpClient,HttpHeaders,HttpParams } from '@angular/common/http';
import { environment } from '../environments/environment';
import { Router } from '@angular/router';
import { Observable } from 'rxjs';

//import { AuthserviceService} from './authservice.service';
declare let L: any;

@Injectable({
  providedIn: 'root'
})
export class DashboardService {
  public datas: any[];
  public mac: any;
  public ssid: any;
  // public signals:any;
  // public jammers:any[];
  public sensors: any[];
  public lt: number;
  public ln: number;
  //public jamst:any;
  public id: string;
  jammer: any;
  public drones: any;
  public Drone: any;
  Droneid: string;
  latlong: any = [];
  public dataforlogin: any[];
  public profile: any;
  public userslogin: any;
  public usertype: string;
  public usersloginstatus: any
  constructor(private http: HttpClient,private router: Router) {
  }

  create(post,token) {
    let httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json','Authorization': 'Token ' + token
      })
    };
    this.http.get(environment.apiUrl + '/api/wifi/signals',httpOptions).subscribe(
      (datas: any[]) => {

        // localStorage.setItem("datas",JSON.stringify(datas));
        //this.router.navigate(['/dashboard']);
      },err)
      }
    );
  }

  //api  for drones
  dronedetails(): Observable<object> {
    let httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json','Authorization': 'Token ' + localStorage.getItem('token')
      })
    };

    return this.http.get(environment.apiUrl + '/api/data/json',httpOptions)
    
  }
  
  setValues() {

  }
  
  sensordetails(): Observable<any> {
    let httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json','Authorization': 'Token ' + localStorage.getItem('token')
      })
    };
    return this.http.get(environment.apiUrl + '/api/sensors',httpOptions)

}
jammerdetails(): Observable<any> {
    let httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json','Authorization': 'Token ' + localStorage.getItem('token')
      })
    };
    return this.http.get(environment.apiUrl + '/api/jammers',httpOptions)
    //for lastlogin users

  }


  userslastlogin(): Observable<any> {
    let httpOptions = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json','Authorization': 'Token ' + localStorage.getItem('token')
      })
    };
    return this.http.get(environment.apiUrl +'/api/activity/loginusers',httpOptions)

  }
  }

dashboard.service.spec.ts


import { Testbed } from '@angular/core/testing';

import { DashboardService } from './dashboard.service';

describe('DashboardService',() => {
  beforeEach(() => Testbed.configureTestingModule({}));

  it('should be created',() => {
    const service: DashboardService = Testbed.get(DashboardService);
    expect(service).toBeTruthy();
  });
});


我尝试了多种方法来克服此问题,但我无法解决

有人可以帮我吗?

解决方法

您需要导入HttpClientTestingModule,并模拟您的服务。

import {} from ''; // Your imports

describe('DashboardService',() => {
  let service: DashboardService;

  const dashboardServiceMock = jasmine.createSpyObj('DashboardService',{
    userslastlogin => of({})
  });

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],providers: [
        { provide: DashboardService,useValue: dashboardServiceMock }
      ]
    });
    service = TestBed.inject(DashboardService);
  });

  // ...

});
,

HttpClientModule 添加到 imports 中的 module.ts 解决了我的问题

    imports: [
    HttpClientModule
  ],