#javascript #angular #typescript #unit-testing #karma-jasmine
#javascript #angular #typescript #модульное тестирование #карма-жасмин
Вопрос:
В моем приложении angular я успешно создал веб-страницу. И он выполнен отлично.
Но когда я тестировал с помощью ng-теста, он показывает некоторые ошибки в 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();
}));*/
});
Я пробовал несколько способов преодолеть это, но я не могу это решить.
Кто-нибудь может мне помочь в этом.
Комментарии:
1. пожалуйста, не стесняйтесь также голосовать
Ответ №1:
Ошибка связана с SuperUserComponent
spec
файлом, которым вы поделились DashboardService
.
Независимо от этого, вы должны создать Mock
сервис DashboardService
и использовать его 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. Для этого вашего кода вы можете обратиться к этой статье, где я упомянул о заглушках и шпионах с рекомендациями