I have a component with a handleAdd
function. This function calls a library, which in turn calls axios
and returns a promise. Once that's resolved, the handleAdd()
method updates component state which in turns renders child(ren).
In other words, it checks with the server first to make sure the item is added before displaying it locally.
When testing with Jest, i have to await sleep for a few msec before the expect runs otherwise the shallow render isn't updated yet, even though I mock/overwrite the api call. There's some delay between the promise resolving, rerender and expect(). Here's what that kind of looks like:
it('adds a thing', async () => {
ThingManager.default.addPlan = () => {
const response = new Promise((resolve, reject) => { resolve() })
return response;
}
const wrapper = shallow(<Home />)
wrapper.find('button').simulate('click')
const input = wrapper.find('#plan-title')
input.simulate('change', { target: { value: 'TEST ITEM' } })
await sleep(500) // without it, <Thing /> isn't rendered yet.
expect(wrapper.find('Thing').length).toBe(1)
});
What's the proper way of doing this?