Callback response in Jest is different than normal response

248 Views Asked by At

I have a method that calls an endpoint in React Native and I want to test it with jest. Everything is asynchronous and it works but the callback response when the function is called in testing side is totally different than the response when the function is called normally in application.

Normally, my response will be a JSON like this:

"_bodyBlob":{
      "_data":{
         "__collector":[
            "Object"
         ],
         "blobId":"43564E12-D797-4971-80C7-A6E06D690F8A",
         "name":"login",
         "offset":0,
         "size":784,
         "type":"application/json"
      }
   },
   "_bodyInit":{
      "_data":{
         "__collector":[
            "Object"
         ],
         "blobId":"43564E12-D797-4971-80C7-A6E06D690F8A",
         "name":"login",
         "offset":0,
         "size":784,
         "type":"application/json"
      }
   },
   "bodyUsed":false,
   "headers":{
      "map":{
         //a lot of private data here and others
      }
   },
   "ok":true,
   "status":200,
   "statusText":"",
   "type":"default",
   "url":"private url"
}

But the response that is returned when called the method by Jest is like this:

Response {
      size: 0,
      timeout: 0,
      [Symbol(Body internals)]: { body: <Buffer >, disturbed: false, error: null },
      [Symbol(Response internals)]: {
        url: undefined,
        status: 200,
        statusText: 'OK',
        headers: Headers { [Symbol(map)]: [Object: null prototype] },
        counter: undefined
      }
    }

Which is not even a JSON.

Is this a normal response for a callback when the method is called by Jest or could be something wrong while I call the function because it's all asynchronous?

Thank you for your time.

1

There are 1 best solutions below

1
On

It seems in your Jest test the response is the javascript Response object: https://developer.mozilla.org/en-US/docs/Web/API/Response

In order to get the JSON out of it, you need to apply its json() method like in this example: https://developer.mozilla.org/en-US/docs/Web/API/Response#an_ajax_call

So once you get the response object, do this:

const jsonValue = await response.json();

The reason why the value is different in jest and in your actual application could be that in your actual application, the library handling the response probably calls the json object before passing you the response.