簡體   English   中英

在 Angular 應用程序中運行 ng 測試時出現空注入器錯誤

[英]Getting the null injector errors while running ng test in angular application

在我的 angular 應用程序中,我成功地創建了一個網頁。 它完美地執行。

但是當我使用 ng test 進行測試時,它在業力中顯示了一些錯誤。 喜歡

在此處輸入圖片說明

超級用戶.component.ts


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


@Component({
  selector: 'app-superuser',
  templateUrl: './superuser.component.html',
  styleUrls: ['./superuser.component.css']
})
export class SuperuserComponent 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.userslastlogin();
    //this.ds.dronedetails(localStorage.getItem('token'));
    this.ds.userslastlogin()
      .subscribe((usersloginstatus) => {
        this.usersloginstatus = usersloginstatus;

        console.log('obj4', usersloginstatus);
        this.superuser = this.usersloginstatus.superuser;
       // this.superuser.sort((a,b) => a.last_login.localeCompare(b.last_login));
        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,  httpOptions).subscribe(
      (dataforlogin) => {
        console.log(dataforlogin);
  
      },
      err => {
        console.log("Error", err)
      }
  
    );
  
  }

}

儀表板.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';

declare let L: any;

@Injectable({
  providedIn: 'root'
})
export class DashboardService {
  public datas: any[];
  public mac: any;
  public ssid: any;
  public sensors: any[];
  public id: string;
  jammer: any;
  public drones: any;
  public Drone: any;
 public dataforlogin: any[];
  public profile: any;
  public userslogin: any;
  public usertype: string;
  public usersloginstatus: any
  getData: any;
  constructor(private http: HttpClient, private router: Router) {
  }

  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)

  }
  }

儀表板.service.spec.ts

import { inject, TestBed } from '@angular/core/testing';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { DashboardService } from './dashboard.service';
import { HttpClient,HttpClientModule, HttpErrorResponse } from '@angular/common/http';

describe('DashboardService', () => {

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

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

  /*it('should be created', inject([DashboardService], (service:DashboardService) => {
    expect(service).toBeTruthy();
  }));*/


});

我嘗試了多種方法來克服這個問題,但我無法解決它。

任何人都可以幫我解決這個問題。

錯誤出在SuperUserComponent ,您共享的spec文件屬於DashboardService

useClass ,您應該創建DashboardServiceMock服務並將其與useClass一起useClass

讓我在super-user.component.spec.ts幫助您:


class export MockDashboardService{
    userslastlogin(){
      return of({
         // whatever response is returned by http call as per the actual service
      })
    }
}

describe('SuperuserComponent', () => {
    let component: SuperuserComponent;
    let fixture: ComponentFixture<SuperuserComponent>;

       beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [SuperuserComponent],
            imports: [ ... required imports],
            providers: [
                { provide: DashboardService, useClass: MockDashboardService},

                // similarly replace other services
            ]
        }).compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(SuperuserComponent);
        component = fixture.componentInstance;
    })

});

如果你是 karma 和 Jasmine 的新手,你可以參考我的這篇文章 對於你的這段代碼,你可以參考這篇文章,其中我提到了關於存根和間諜的最佳實踐

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM