import { createUser } from '../services'; ... ... handleFormSubmit = () => { this.setState({ loading: true }); createUser() .then(() => { this.setState({ loading: false, }); }) .catch(e => { this.setState({ error: e, }); }); };
it('rejects...', () => { const Container = createUserContainer(CreateUser); const wrapper = shallow(<Container />); return wrapper.instance().handleFormSubmit() .catch(e => { console.log("State: ", wrapper.state()); expect(e).toEqual('error'); }); });
export const createUser = function() { return new Promise((resolve, reject) => { reject('error'); }); };
The test does force the code to go into the catch in the method. So the state does get set to 'error'.
But in my test, it doesn't do what I expect and wait for the Promise to reject before it tests for the state change. I'm not sure what to try here, should I be using async/await?
So it's the createUser
method I want to wait for but I'm not sure my implementation allows for this.
It looks like using try-catch with async/await is the easiest way to achieve this as the rejected value is thrown: it("rejects (bad)", async () => { try { await promiseMe("Error"); } catch (e) { expect(e). toEqual("Error"); } }); But wait.
You can chain promises with await if you choose to. function generateException() { return new Promise(reject => { return reject(new Error('Promise Rejected'); }) it('should give an error', async ()=> { await generateException(). catch(error => { expect(error. message).to.
You can also use the . resolves matcher in your expect statement, and Jest will wait for that promise to resolve. If the promise is rejected, the test will automatically fail. return expect(fetchData()).
We call jest. mock('../request') to tell Jest to use our manual mock. it expects the return value to be a Promise that is going to be resolved. You can chain as many Promises as you like and call expect at any time, as long as you return a Promise at the end.
You should do something like this:
it('rejects...', () => { const Container = createUserContainer(CreateUser); const wrapper = shallow(<Container />); return expect(wrapper.instance().handleFormSubmit()).rejects.toEqual('error'); });
I think it is cleaner this way. You can see this approach in the official docs.
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