【发布时间】:2020-05-09 03:39:28
【问题描述】:
我有一个 Angular 项目,我想为其编写单元测试。每当测试到达代码中的 getAlert 函数时,我都会收到此错误:失败:this.alertController.getAlerts 不是函数。我不知道在这里做什么。
alert.component.ts
import {Component, OnInit} from '@angular/core';
import {AlertController} from '../../controllers/AlertController';
import {Alert} from '../../entities/Alert';
@Component({
selector: 'app-alert',
templateUrl: './alert.component.html',
styleUrls: ['./alert.component.css']
})
export class AlertComponent implements OnInit {
alerts: Alert[];
constructor(private alertController: AlertController) {
}
ngOnInit(): void {
this.alertController.getAlerts().subscribe(alert => {
this.alerts = alert;
});
}
}
alert.component.spec.ts
import {async, TestBed} from '@angular/core/testing';
import {FormsModule} from '@angular/forms';
import {HttpClientModule} from '@angular/common/http';
import {RouterTestingModule} from '@angular/router/testing';
import {CUSTOM_ELEMENTS_SCHEMA} from '@angular/core';
import {AlertComponent} from './alert.component';
import {of} from 'rxjs';
import {AlertController} from '../../controllers/AlertController';
const alertServiceStub = {
get() {
const alert = [
{
alertId: 1,
alertMessage: 'test message',
transactionContext: null,
state: null
}];
return of( alert );
}
};
describe('RuleOverViewComponentTest', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AlertComponent
],
imports: [FormsModule, HttpClientModule, RouterTestingModule],
providers: [AlertComponent, {provide: AlertController, useValue: alertServiceStub}],
schemas: [
CUSTOM_ELEMENTS_SCHEMA
]
}).compileComponents();
}));
it('should create the component', async(() => {
const fixture = TestBed.createComponent(AlertComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
it('should create the component', async(() => {
const fixture = TestBed.createComponent(AlertComponent);
fixture.detectChanges();
expect(document.querySelectorAll('#alert').length).toEqual(1);
}));
});
AlertController.ts
@Injectable({
providedIn: 'root'
})
export class AlertController {
alertUrl: string;
constructor(
private httpClient: HttpClient
) {
this.alertUrl = 'http://localhost:8091/alert-service/';
}
public getAlerts(): Observable<Alert[]> {
return this.httpClient.get<Alert[]>(this.alertUrl + 'alert');
}
public getAlert(alertId: number): Observable<Alert> {
return this.httpClient.get<Alert>(this.alertUrl + 'alert/' + alertId);
}
public blockCard(alertId: number) {
return this.httpClient.post(this.alertUrl + 'blockCard/', alertId);
}
public closeAlert(alertId: number) {
return this.httpClient.post(this.alertUrl + 'closeAlert', alertId);
}
}
我尝试进行的每个测试中的每个功能都得到了这个。但据我所知,我制作函数的方式非常好。那么到底发生了什么,我怎样才能使测试成功。
【问题讨论】:
标签: angular typescript jasmine karma-runner