How to trigger transitionend with Jest unit testing

Viewed 1230

I am using angular 8 and Jest for unit testing. I have added a listener for 'transitionend' on the element, but I haven't been able to figure out how to trigger/mock the transitionend event with Jest

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

I am trying to create a unit test that tests this.transitionEnded is true

2 Answers

I was able to figure out something that worked for me

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);
});

Use this helper function to trigger any event:

function triggerTransitionEnd(element) {
   let event = document.createEvent("Event");
   event.initEvent("transitionend", true, true);
   element.dispatchEvent(event);
}

And then in your test use it like so:

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