Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I properly test for a rejected promise using Jest?

Code

import { createUser } from '../services'; ... ...  handleFormSubmit = () => {     this.setState({ loading: true });   createUser()     .then(() => {       this.setState({         loading: false,       });     })     .catch(e => {        this.setState({          error: e,        });     }); }; 

Test

 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');       });  }); 

Mock

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.

like image 724
coding123 Avatar asked Jun 12 '18 16:06

coding123


People also ask

How do you test Promise reject in Jest?

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.

How do you assert Promise reject?

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.

How do you resolve a Promise in Jest?

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()).

How do you mock a Promise response in Jest?

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.


Video Answer


1 Answers

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.

like image 62
Andres Gardiol Avatar answered Oct 26 '22 05:10

Andres Gardiol