Jasmine: Preventing unhandled promise rejections from failing your test

Posted . Visible to the public.

You have an async function that rejects:

async function failingFunction() {
  throw new Error("Something went wrong")
}

When you call that function in a test, your test will fail:

it('has a test', function() {
  failingFunction() // this will fail your test
})

The failure message will look like this:

Unhandled promise rejection: Error: Something went wrong

You can fix this by expecting the state of the returned promise:

it('has a test', async function() {
  await expectAsync(failingFunction()).toBeRejected()
})

When you cannot access the rejecting promise

Sometimes you will not have access to the rejecting promise. This can happen if the failing function is called by another function, but its rejecting promise is never returned:

function wrappingFunction() {
  // Note we're not returning the promise
  failingFunction()
}

it('has a test', function() {
  wrappingFunction() // no way to expect the promise state
})

In this case you can use jasmine.spyOnGlobalErrorsAsync() Show archive.org snapshot to temporarily disable Jasmine's detection of unhandled errors:

it('has a test', async function() {
  await jasmine.spyOnGlobalErrorsAsync(async function() {
    wrappingFunction()
  })  
})

You can even make assertions on the unhandled error by accepting a spy in the callback:

it('has a test', async function() {
  await jasmine.spyOnGlobalErrorsAsync(async function(globalErrorSpy) {
    wrappingFunction()
    
    expect(globalErrorSpy).toHaveBeenCalledWith(jasmine.any(Error))
  })  
})

How can Jasmine see an unhandled error?

Jasmine can detect unhandled errors by listening to the global error Show archive.org snapshot and unhandledrejection Show archive.org snapshot events.

Henning Koch
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2023-05-31 15:13)