How do I properly test for a rejected promise using Jest?
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.
The test fails because it's not aware that the subject is asynchronous. It can be fixed by using a done
param or making the test function async
.
Note it's also necessary to set the number of expected assertions so that the test will fail even if the catch branch is not taken.
async
/await
style:
it('rejects...', async () => { expect.assertions(1); const Container = createUserContainer(CreateUser); const wrapper = shallow(<Container />); await wrapper.instance().handleFormSubmit() .catch(e => { console.log("State: ", wrapper.state()); expect(e).toEqual('error'); }); });
Older style done
param:
it('rejects...', done => { expect.assertions(1); const Container = createUserContainer(CreateUser); const wrapper = shallow(<Container />); wrapper.instance().handleFormSubmit() .catch(e => { console.log("State: ", wrapper.state()); expect(e).toEqual('error'); done(); }); });
Your code looks correct. Why do you say that it doesn't wait for the Promise to reject? The only difference I would make would be to make use of Jest's mocking capability, so change
Mock
export const createUser = function() { return new Promise((resolve, reject) => { reject('error'); });};
to
Test
jest.mock('../services');const services = require('../services');const createUser = jest.spyOn(services, "createUser");createUser.mockRejectedValue("error");...it('rejects...', () => {
There's no need to have a separate Mock file