How do I fetch-mock an accurate server error?

1.9k views Asked by At

The issue:

fetchmock

fetchMock.get('glob:https://*/server-api-uri', () => {
  throw { example: 'error' }
})

Source JS file:

exampleServerCall().catch(error => {
  console.log(error) // error = "[ object object ]" :(
})

So my catch statements are returning with a useless "[ object object ]" string when what I really want is access to the full mocked server error.

1

There are 1 answers

0
Daniel Tonon On

After reading the MDN docs for throw, I found documentation for how to throw a custom object in a throw handler.

You need to do it by creating a custom class object.

fetchmock

class CustomError {
    example = 'error'
}

fetchMock.get('glob:https://*/server-api-uri', () => {
  throw new CustomError()
})

source JS file:

exampleServerCall().catch(error => {
  console.log(error) // error = { example: 'error' } :D
})