jefflau / jest-fetch-mock

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

mock responses that are not ok #86

Closed michaelknoch closed 5 years ago

michaelknoch commented 5 years ago

I did not realy get how to mock a realistic fetch failing behaviour. As described in this article fetch only rejects promises if network errors happen. So for example if the server returns a 500, fetch normally would resolve a promise with {response: { ok: false }}.

Is it possible to mock such a response?

fetch.mockResponse({ ok: false });

does not seem to work as expected

jefflau commented 5 years ago

When you say it does not seem to work as expected - what happens?

jest-fetch-mock allows you pass a Response object, so whatever you usually get in that you should be able to mock.

https://developer.mozilla.org/en-US/docs/Web/API/Response

michaelknoch commented 5 years ago

it was my bad @jefflau, i havent seen the second parameter

fetch.mockResponseOnce(JSON.stringify("fail"), { status: 401, ok: false });
TerrorOnMtHyjal commented 5 years ago

This does not work for me.

fetch.once(JSON.stringify('testdata'), {ok: false});

results in:

Argument of type '{ok: boolean;}' is not assignable to parameter of type 'MockParams'. Object literal may only specify known properties, and 'ok' does not exist in type 'MockParams';

Thoughts?

joel-s commented 2 years ago

This works for me; apparently ok gets set to false based on the status code.

    fetchMock.mockResponseOnce(
      JSON.stringify('Ignore this'),
      { status: 500, statusText: 'Server error' },
    );