How to time travel to end of animation using React Jest
Asked Answered
E

2

10

I'm trying to test a component which change state after a TweenMax animation. Everything's fine on browser, but I cannot understand how to write a test for it.

The problem is Jest doesn't wait for the animation to complete, therefore state doesn't change.

I also tried with jest.runAllTicks() and jest.runAllTimers()

Here some code that would eventually simulate what I'm working on:

Component

class HelloWorld extends React.Component {
    constructor(props) {
        super(props);
        this.state = { done: false };
        this.p;
    }

    componentDiDMount() {
        TweenMax.to(ReactDOM.findDOMNOde(this.p), 1, { 
            onComplete: () => {
                this.setState({ done: true })
            }
        })
    }

    renderMessage() {
        if (this.state.done) {
            return "Hello World";
        } else {
            return "Loading...";
        }
    }

    render () {
        return <p ref={p => this.p = p}>{this.renderMessage()}</p>;
    }       
}

Test (basic structure)

describe("test",()=>{
    it("works", ()=>{
        const component = mount(<HelloWorld />);
        // ...wait some time (or pretend to)
        expect(component.find(p).text()).toEqual("Hello World");
    })
})
Ecosystem answered 16/5, 2018 at 9:33 Comment(0)
E
2

Digging into Jest documentation I've found that you can specify a done parameter which will force the test to wait until done() is called.

This way it's possible to set a timeout and wait for the animation to complete.

See Jest callbacks documentation

describe("test",() => {
    it("works", done => {
        const component = mount(<HelloWorld />);
        setTimeout(() => {
            expect(component.find(p).text()).toEqual("Hello World");
            done();
        }, 1100);
    })
})
Ecosystem answered 16/5, 2018 at 10:10 Comment(0)
N
0

Actually you can trigger it with:

const element = document.getElementById('yourElement');
fireEvent.animationEnd(element);
Neocolonialism answered 5/3 at 14:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.