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:
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>;
}
}
describe("test",()=>{
it("works", ()=>{
const component = mount(<HelloWorld />);
// ...wait some time (or pretend to)
expect(component.find(p).text()).toEqual("Hello World");
})
})
To run the end-to-end test, we'll use react-scripts , which has Jest installed internally. Modify the package. json file and add the code below to the scripts object: "test": "react-scripts test --testPathIgnorePatterns=.
jest. setTimeout(30000); test('some test title', async () => { const foo = true; await new Promise((r) => setTimeout(r, 2000)); expect(foo). toBeDefined(); }); We've shown how to use programming to solve the Jest Wait For X Seconds problem with a slew of examples.
jest-date-mock is a complete javascript module wrote by me, and it is used to test Date on jest. import { advanceBy, advanceTo } from 'jest-date-mock'; test('usage', () => { advanceTo(new Date(2018, 5, 27, 0, 0, 0)); // reset to date time. const now = Date.
Shallow rendering is one way that Enzyme keeps tests simpler than Jest. When you shallow-render a component with Enzyme, you render only that component. Enzyme doesn't render any of the children of that component. This is a useful restriction that ensures that you aren't testing too much in one test.
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);
})
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With