timkindberg / jest-when

Jest support for mock argument-matched return values.
MIT License
734 stars 38 forks source link

Promise rejection was handled asynchronously #90

Open jinganix opened 2 years ago

jinganix commented 2 years ago

(node:16003) PromiseRejectionHandledWarning: Promise rejection was handled asynchronously (rejection id: 1) at handledRejection

In my test, I mock rejected value without calledWith, then I get the errors.

  when(mockFn)
    .mockRejectedValue({})

If I make it with calledWith, it works:

  when(mockFn)
    .calledWith(expect.anything())
    .mockRejectedValue({})

I get this error then I change jest-when CODE from

    this.mockResolvedValue = returnValue => this.mockReturnValue(Promise.resolve(returnValue))
    this.mockRejectedValue = err => this.mockReturnValue(Promise.reject(err))

to

    this.mockResolvedValue = returnValue => this.mockImplementation(() => Promise.resolve(returnValue))
    this.mockRejectedValue = err => this.mockImplementation(() => Promise.reject(err))

It seems work. I think that because Promise computed too early. Is that right?

timkindberg commented 2 years ago

Can I see a bit of your code and unit test code?

I just added unit tests and they are passing without any code changes. How is your test different than these?

it('can default a resolved value alone', async () => {
  const fn = jest.fn()

  when(fn)
    .defaultResolvedValue('default')

  await expect(fn('bar')).resolves.toEqual('default')
  await expect(fn('foo')).resolves.toEqual('default')
})

it('can default a rejected value alone', async () => {
  const fn = jest.fn()

  when(fn)
    .defaultRejectedValue(new Error('default'))

  await expect(fn('bar')).rejects.toThrow('default')
  await expect(fn('foo')).rejects.toThrow('default')
})
jinganix commented 2 years ago

We use react, and the mocked function is passed through props. But I am not sure which one caused the warning. We have already changed them to when(mockFn).calledWith(expect.anything()).mockRejectedValue({}), they work properly now.

BenSayers commented 1 year ago

I am having this issue too. This test case exposes the problem:

it('does not create a rejected promise when no unmatched calls are made (defaultReturnValue alias)', async () => {
  const fn = jest.fn()

  when(fn)
    .calledWith(expect.anything())
    .mockResolvedValueOnce(true)
    .defaultRejectedValue(false)

  await expect(fn('anything')).resolves.toEqual(true)
})