Albiona Hoti
Albiona Hoti

Reputation: 33

UnhandledPromiseRejectionWarning:

I'm trying to test ReactJs components, where one of them has a method in which it fetches data, the fetch has a promise in it.. So I tried to create a mock file:

  const apiFetch = {
      value() {
        return 42
      },
    }

module.exports = apiFetch

then:

const spy = jest.spyOn(apiFetch, 'value')

const isValue = apiFetch.value()

expect(spy).toHaveBeenCalled()

expect(isValue).toBe(42)

The test is passing, but this warning is still showing.

I added one more thing:

process.on('UnhandledPromiseRejectionWarning', (e) => { throw e })

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: 188)

Upvotes: 1

Views: 9393

Answers (1)

Martín Zaragoza
Martín Zaragoza

Reputation: 1817

When running async tests you should keep in mind that you need to indicate the test method when it has finished.

With jest you can do something like:

apiFetch.js

const apiFetch = {
    value() {
        return Promise.resolve(42);
    },
}

module.exports = apiFetch

apiFetch.test.js:

const apiFetch = require('./apiFetch');

test('the data is peanut butter', done => {
    apiFetch.value().then(data => {
        expect(data).toBe(42);
        done();
    })
});

done is an injected function parameter (provided by the jest framework) that when called, indicates the end of the test method.

If you're testing async logic without using the async features of jest (or mocha) then tests will pass even though the async promises fail

edit

Each framework has promise support. With jest it is something like

it('works with resolves', () => {
   expect.assertions(1);
   return expect(apiFetch.value()).resolves.toEqual(42);
});

When working with pure callbacks, use the injected done.

When working with promises you could use the injected 'done' function, but if the promise fails and 'done' is not called, then the test will fail on timeout. With jest it is recommended to work with 'it' , 'expect' and 'resolve' when testing promise logic.

Upvotes: 6

Related Questions