在 angular 应用程序中进行 运行 ng 测试时获取空注入器错误
Getting the null injector errors while running ng test in angular application
在我的 angular 应用程序中,我已经成功创建了一个网页。并且执行得很完美。
但是当我使用 ng test 进行测试时,它显示了一些 karma 错误。喜欢
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)
}
);
}
}
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)
}
}
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();
}));*/
});
我尝试了多种方法来克服这个问题,但我无法解决它。
谁能帮我解决这个问题。
错误与 SuperUserComponent
有关,您共享的 spec
文件属于 DashboardService
。
无论如何,您应该创建 DashboardService
的 Mock
服务并将其与 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;
})
});
您可以参考 this article of mine if you are new to karma and Jasmine. For this code of yours, you can refer this article where I have mentioned about stubs and spies 最佳实践
在我的 angular 应用程序中,我已经成功创建了一个网页。并且执行得很完美。
但是当我使用 ng test 进行测试时,它显示了一些 karma 错误。喜欢
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)
}
);
}
}
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)
}
}
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();
}));*/
});
我尝试了多种方法来克服这个问题,但我无法解决它。
谁能帮我解决这个问题。
错误与 SuperUserComponent
有关,您共享的 spec
文件属于 DashboardService
。
无论如何,您应该创建 DashboardService
的 Mock
服务并将其与 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;
})
});
您可以参考 this article of mine if you are new to karma and Jasmine. For this code of yours, you can refer this article where I have mentioned about stubs and spies 最佳实践