我正在尝试测试模态组件中的 closeModal 函数在单击模态上的"关闭按钮"时是否正常工作,但是此测试将我的按钮元素显示为空。我收到错误"无法读取 null 的属性'触发器事件处理程序'"。我该如何解决这个问题?
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="enableClose">Close</button>
上。您需要先将enableClose
设置为 true,然后才能尝试访问它。尝试这样的事情:
it("should test closeModal method on close button", () => {
spyOn(component, "closeModal")
component.enableClose = true; // set your variable to true
fixture.detectChanges(); // update everything to reflect the true state
let el = fixture.debugElement.query(By.css('#close'))
el.triggerEventHandler('click', null)
fixture.detectChanges()
fixture.whenStable().then(() => {
expect(component.closeModal).toHaveBeenCalled();
});
});
另外,我注意到在您的html中关闭按钮的id为button
,但是在您的测试中,您正在寻找#close
,这是否正确,这意味着您的按钮ID应该close
?