【发布时间】:2018-07-03 18:17:02
【问题描述】:
我正在尝试在单击模态组件上的“关闭按钮”时测试模态组件中的 closeModal 函数是否正常工作,但是此测试将我的按钮元素显示为空。我收到错误“无法读取 null 的属性‘triggerEventHandler’。”我该如何解决这个问题?
modal.component.ts
import { AppComponent } from "./../app.component";
import { async, ComponentFixture, TestBed } from "@angular/core/testing";
import { ModalComponent } from "./modal.component";
import { By } from '@angular/platform-browser';
describe("ModalComponent", () => {
let component: ModalComponent;
let fixture: ComponentFixture<ModalComponent>;
beforeEach(
async(() => {
TestBed.configureTestingModule({
declarations: [ModalComponent, AppComponent]
}).compileComponents();
})
);
beforeEach(() => {
fixture = TestBed.createComponent(ModalComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it("should create", () => {
expect(component).toBeTruthy();
});
it("should test closeModal method on close button", () => {
spyOn(component, "closeModal")
let el = fixture.debugElement.query(By.css('#close'))
el.triggerEventHandler('click', null)
fixture.detectChanges()
fixture.whenStable().then(() => {
expect(component.closeModal).toHaveBeenCalled();
});
});
});
modal.component.html
<div class="ds-c-dialog-wrap"[ngClass]="hideModal ? 'hide' : 'show'">
<div>
<header role="banner">
<h1 id="dialog-title">{{modalTitle}}</h1>
<button
id="button"
(click)="closeModal()"
*ngIf="enableClose">Close</button>
</header>
<main>
<p class="ds-text">
{{modalBody}}
</main>
<aside role="complementary">
<button>Dialog action</button>
<button *ngIf="enableCancel" (click)="closeModal()">Cancel</button>
</aside>
</div>
</div>
【问题讨论】:
-
我正在关注这个。我遇到了几乎完全相同的问题,但我使用的是
*ngIf。我知道这是因为条件尚未设置为 true,因此测试无法看到该元素。我确定我们需要先设置条件并执行fixture.detectChanges(),然后再执行triggerEventHandler()。 -
我的 *ngIf 条件为真,但仍无法识别元素。如果您找到解决方案,请告诉我
标签: javascript angular unit-testing karma-jasmine