You need to enable JavaScript to run this app. Angular应用运行ng test触发Karma测试时出现null injector错误求助
优惠活动
大模型
产品
解决方案
定价
更多

Angular应用运行ng test触发Karma测试时出现null injector错误求助

Angular 单元测试 NullInjector 报错问题说明

问题背景

  • 在Angular应用开发过程中,已完成对应页面模块的开发与功能验证,页面在正常运行场景下可完美执行全部逻辑
  • 执行ng test命令触发单元测试时,Karma测试控制台抛出NullInjector类型的相关报错

涉及核心代码文件

1. superuser.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)
      }
  
    );
  
  }

}

2. 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';

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)

  }
  }

3. dashboard.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();
  }));*/


});

排查进展

  • 已尝试多种调整方案排查该问题,始终未能定位根因并解决报错,希望获得针对性技术指导

内容的提问来源于stack exchange,提问作者Haritha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.11.22 02:24:00