如何使用Jest单元测试触发transitionend事件

3

我正在使用Angular 8和Jest进行单元测试。我在元素上添加了一个' transitionend '监听器,但是我还没有找到使用Jest触发/模拟'transitionend'事件的方法。

this.animatedElement.nativeElement.addEventListener('transitionend', () => {
      this.transitionEnded = true;
});

我正在尝试创建一个单元测试,测试this.transitionEnded是否为真

2个回答

2
使用此辅助函数来触发任何事件:
function triggerTransitionEnd(element) {
   let event = document.createEvent("Event");
   event.initEvent("transitionend", true, true);
   element.dispatchEvent(event);
}

然后在你的测试中像这样使用它:

test("Some description here", () => {
    const popup = document.getElementById("popup");
    triggerTransitionEnd(popup);
    expect(popup.classList.contains("show")).toBeFalsy();
});

1
我能够找到适合我的解决方案。
it('Should set transitionEnded to true', () => {
    // created 'transitionend' event
    const event = new Event('transitionend');
    const component = TextBed.createComponent(AppComponent).componentInstance;

    // call method that adds event listener to animatedElement
    component.methodToAddListener();
    // dispatch event that you created on animatedElement
    component.animatedElement.nativeElement.dispatchEvent(event);

    expect(component.transitionEnded).toBe(true);
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接