Fak*_*ire 5 javascript unit-testing karma-jasmine angular
我试图测试当单击模态上的“关闭按钮”时模态组件中的 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();
});
});
});
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
Mik*_*ike 10
我相信你的问题是*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();
});
});
Run Code Online (Sandbox Code Playgroud)
另外,我注意到在您的 html 中关闭按钮的 id 为button,但在您的测试中您正在寻找#close,这是否正确,这意味着您的按钮 id 应该是close?
| 归档时间: |
|
| 查看次数: |
8704 次 |
| 最近记录: |