jefflau / jest-fetch-mock

Jest mock for fetch
MIT License
886 stars 117 forks source link

allow to inject argument for Promise.reject() into mockReject and mockRejectOnce #33

Closed akleiber closed 6 years ago

akleiber commented 6 years ago

While using mockReject() or mockRejectOnce() it could be practical to allow to define the reason of the rejection. Currently both methods just do a Promise.reject() without any argument.

Scenario:

function collect (data, callback) {
  fetch('someUrl', init)
   .catch((error) => {
     callback(error)
   })
}

const callback = (error, response) => {
  //do something on error
}
collect({some: 'data'}, callback)

What I think would be nice to have:

test('test if callback is getting called with error argument', (done) => {
  fetch.mockRejectOnce(new Error('boom'))
  const callback = function (error) {
    expect(error).toEqual(expect.any(Error))
    done()
  }
 collect({}, callback)
})

If this is something you would support I will create a PR.

jefflau commented 6 years ago

Paging @hally9k who implemented this initial reject mocks.

AllenFang commented 6 years ago

any progress here? I think I can open a PR for this if necessary :)

brettpostin commented 6 years ago

I'm trying to use this in conjunction with redux-api-middleware.

mockReject() causes e.message to fail as the error is undefined. I suspect the above PR would help solve that but would it also be possible to return an empty Error object if not defined?

AllenFang commented 6 years ago

above PR is just allow to pass any data to mockReject and resolve it from promise. so you can pass anything by yourself.

jefflau commented 6 years ago

Merged and published to NPM.