gpt4 book ai didi

javascript - Karma 单元测试中的错误 'Cannot read property ' triggerEventHandler' of null'

转载 作者:太空狗 更新时间:2023-10-29 17:51:31 30 4
gpt4 key购买 nike

我正在尝试测试在单击模态上的“关闭按钮”时模态组件中的 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="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

关于javascript - Karma 单元测试中的错误 'Cannot read property ' triggerEventHandler' of null',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48426944/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com