jefflau / jest-fetch-mock

Jest mock for fetch
MIT License
883 stars 116 forks source link

mockResponseOnce returns entire response instead of just body #115

Closed joelwmale closed 5 years ago

joelwmale commented 5 years ago

I have the following code in a component of mine:

  componentWillMount() {
    authService.getCustomerDetailsForToken(this.token)
      .then((res: ITokenResponse) => {
        this.setState({
          tokenResponse: res
        });
      })
      .catch(() => {
        this.errors = 'error';
      });
  }

This component works, and res is an object of values, like first_name, last_name etc.

When running the test using the following mockResponseOnce:

    fetch.mockResponseOnce(JSON.stringify({
      first_name: "Test",
      last_name: "Bob",
    }));

When I console log the state of the component, it seems the tokenResponse is an instance of a Response object:

      { tokenResponse:
         Response {
           size: 0,
           timeout: 0,
           [Symbol(Body internals)]:
            { body: '{"first_name":"Test","last_name":"Bob"}',
              disturbed: false,
              error: null },
           [Symbol(Response internals)]:
            { url: undefined,
              status: 200,
              statusText: 'OK',
              headers: [Object] } },
        confirmed: false }

Where my component expects something similar to:

      { tokenResponse: '{"first_name":"Test","last_name":"Bob"}',
        confirmed: false }

I can make the tokenResponse look like that when doing res.body, but that would not work for the real api the site uses.

However - it seems as something is still wrong with this as I have a p tag that should looks like:

<p>I confirm I am {this.state.tokenResponse.first_name} {this.state.tokenResponse.last_name}</p>

So when the page loads with the real api it looks like:

<p>I confirm I am Test Bob</p>

However, when I force res.body and debug the enzyme instance, I get:

            <p>
              I confirm I am

            </p>

Can anyone see if I'm doing something obvously wrong? I searched through the docs and can't find anything. Been battling my head at this test case for upwards of 3 hours, just trying to mock a response and make sure the view loads the I confirm I am Test Bob...

joelwmale commented 5 years ago

I have fixed it by doing the following in my api response handler:

const data: any = CONFIG.envIsTest ? JSON.parse(res.body as any) : res;