Read more

Jasmine: Preventing unhandled promise rejections from failing your test

Henning Koch
May 31, 2023Software engineer at makandra GmbH

You have an async function that rejects:

async function failingFunction() {
  throw new Error("Something went wrong")
}
Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

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.

Posted by Henning Koch to makandra dev (2023-05-31 17:13)