角度测试:点击按钮输出发射器会为dispatchEvent返回null



我的Angular组件中的函数:

@Output() projectEvent = new EventEmitter<string>();
openProjectDashboard(projectKey: string) {
this.projectEvent.emit(projectKey);
}

HTML:

<div class="project-container">
<div
class="project-card"
*ngFor="let project of projects"
(click)="openProjectDashboard(project.key)"
</div>
....
</div>

我的测试:

beforeEach(() => {
fixture = TestBed.createComponent(ProjectGridComponent);
component = fixture.componentInstance;
fixture.detectChanges();

spyOn(component.projectEvent, "emit");
spyOn(component, "openProjectDashboard");
});
it("should emit event", () => {
// component.openProjectDashboard("DE365");
// expect(component.openProjectDashboard).toHaveBeenCalled();
const nativeElement = fixture.nativeElement;
const div = nativeElement.querySelector(".project-card");
div.dispatchEvent(new Event('click'));
fixture.detectChanges();
expect(component.projectEvent.emit).toHaveBeenCalled();
});

运行测试时出现错误:

错误:TypeError:无法读取空的属性"dispatchEvent">

当您spyOn某个东西时,您将丢失实现细节。您必须调用Through才能保留旧的实现详细信息。

尝试:

beforeEach(() => {
fixture = TestBed.createComponent(ProjectGridComponent);
component = fixture.componentInstance;
fixture.detectChanges();

spyOn(component.projectEvent, "emit");
spyOn(component, "openProjectDashboard").and.callThrough(); // add callThrough here so the function actually runs
});
it("should emit event", () => {
// component.openProjectDashboard("DE365");
// expect(component.openProjectDashboard).toHaveBeenCalled();
const nativeElement = fixture.nativeElement;
const div = nativeElement.querySelector(".project-card");
div.dispatchEvent(new Event('click'));
fixture.detectChanges();
expect(component.projectEvent.emit).toHaveBeenCalled();
});

最新更新