Igor Lacik Igor Lacik - 1 year ago 115
React JSX Question

React test state change after timeout

say I have a Card element that flips when clicked upon. After 2 seconds, it must automatically flip back. In CSS terms, after clicking, the transform style is set to rotateY(180deg), after 2 seconds it should becom Initial

I want to write unit tests for this back-flip (currently the test passes even though I expect the transform prop to equal initial):

it( 'flips', () => {
const testedCard = shallow( <Card /> )
testedCard.setState( { faceUp: true } )

setTimeout(
() => {
const cardFlipper = testedCard.node.props.children
expect( cardFlipper.props.transform ).to.equal( 'initdasddaial' )
},
2500
);
} )

Answer Source

If you are using mocha or jasmine, you can pass a done callback in the it:

it( 'flips', (done) => {
        const testedCard = shallow( <Card /> )
        testedCard.setState( { faceUp: true } )

        setTimeout(
            () => {
                const cardFlipper = testedCard.node.props.children
                expect( cardFlipper.props.transform ).to.equal( 'initdasddaial' )
                done();
            },
            2500
        );
    } )

However, depending on your test runner (settings), the done timeout might occur before 2500 mills. You might have to configure a different timeout value.

As a side note, unit tests based on timing are not usually a good idea. Consider designing the component so that you can test more deterministically.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download