jefflau / jest-fetch-mock

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

support response.json() #120

Closed aslack19 closed 5 years ago

aslack19 commented 5 years ago

So in my domain code I have something like this where I rely on resp.json() to return a Promise.

fetch(url, { method: 'GET' })
    .then(async (resp) => {
      console.log('resp.json', resp.json())
      const json = await resp.json()
      console.log('json', json)
      return JSON.parse(json)
    })

and in my test code I have this:

    fetchMock.mockResponse(
      JSON.stringify(
        {
          status: "OK"
        }))

Running the test I get this error:

    TypeError: body used already for: undefined

      at Response.consumeBody (node_modules/jest-fetch-mock/node_modules/node-fetch/lib/index.js:327:30)

the logging just before the await resp.json() looks like this:

resp Response {
        size: 0,
        timeout: 0,
        [Symbol(Body internals)]: 
         { body: '{"status":"OK"}',
           disturbed: false,
           error: null },
        [Symbol(Response internals)]: 
         { url: undefined,
           status: 200,
           statusText: 'OK',
           headers: Headers { [Symbol(map)]: {} } } }

So anecdotally Body looks good yet Response seems anaemic

Interestingly (possibly) disturbed is false yet when truthy spits out that error message

/// index.js
function consumeBody() {
    var _this4 = this;
         if (this[INTERNALS].disturbed) {
        return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`));
    }
         this[INTERNALS].disturbed = true;
...

the body being processed twice would account for the error but as far as I can tell I am not doing that, possibly something in the resp.json() call is making that happen.

Hopefully I'm just doing something silly ...

aslack19 commented 5 years ago

nm ... I am calling it twice .. my logging calls resp.json() as does my domain code. doh!