1

When I do a shallow of a component, a method_1() get called in componentDidMount() which call an utility method_2() and finally it makes an call to method_3() which is a promise based request. It throws the below error when running npm test

Example: Loginn.spec.js:

const wrapper = shallow(<Login />)
Error: UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)

Flow of the code given below.

Login.js:

import { AuthService } from '../../react-auth';
    componentWillMount() {

        const config = {
            environment: 'qa',
            google: true
        }

        const updateLoginState = function (isBool, currentContext) {
                currentContext.updateState('authStatusCheck', isBool);
        }

         authService.init(config, this, updateLoginState)
    }

Auth.js

import UmsLib from './umsLib'
export default class AuthService{
   init(customOptions, loginContext, updateLoginState) {
          // some code.
           UmsLib.getStatus(customOptions, loginContext, updateLoginState);
   };
}

ums.js

import ums from ‘user-management’;
export class UmsLib{
   getStatus(config, loginContext, updateLoginState) {
        ums.init(this.configOptions)
               .then(user => {
                   console.log("promise-----------------")
                   if (user && ums.isReady) {
                       return updateLoginState(true, loginContext);
                   }
               })
               .catch(error => {
                   throw Error('Failed calling UMS Library', error);
               })
   }
}

I have added try/catch to throw all the possible error and also tried handling promise in the test case, but it seems I am doing wrong something somewhere. Any suggestion would be appreciated.

rabejens
  • 6,290
  • 8
  • 35
  • 77
  • does enzyme shallow call componentWillMount?I think mount calls the lifecycle methods and not shallow? – VivekN Jul 01 '18 at 19:18

1 Answers1

2

That's because of you throw Error inside catch function, which leads to unhandled promise rejection. That's exactly what you got in the console.

The matter is that catch() function returns Promise. From MDN docs:

The Promise returned by catch() is rejected if onRejected throws an error or returns a Promise which is itself rejected; otherwise, it is resolved.

This SOF discussion could also help to understand Promises chaining.

pyotruk
  • 71
  • 1
  • 3