masafood
masafood

Reputation: 375

FetchError: invalid json response body at reason: Unexpected end of JSON input when using mockfetch with Jest

I am using Mockfest to test a very simple api for unsplash. The fetch call works very well of course and it looks like this:

test('it makes a fetch call to unsplash', async () => {
        await api.fetchPhoto('wedding')
        expect(fetch).toHaveBeenCalled()
    })

and it shows from the Jest script:

● it makes a fetch call to unsplash

FetchError: invalid json response body at  reason: Unexpected end of JSON input

  4 |
  5 |     const response = await fetch(url)
> 6 |     const data = await response.json(); 
    |                  ^
  7 |     
  8 |     return data;
  9 | }

This is my fetch function:

async function fetchPhoto (event) {

    const url = 'https://api.unsplash.com/photos/random?query='+event+'&per_page=1&client_id=gKEeCzK-8XXRBG8IHbYAGTEUDMN-Dpm9FjxjDS4f2Y0';

    const response = await fetch(url)
    const data = await response.json(); 
    
    return data;
}

module.exports = { fetchPhoto };
 

How can I get past this error, I mean my fetch function works and returns what its supposed to return.

Upvotes: 3

Views: 12242

Answers (2)

Yonatan Ayalon
Yonatan Ayalon

Reputation: 2045

I also encountered this issue, and even though the JSON data appears valid and the app is working with this data properly - still getting Jest errors.

I "solved" it by adding try / catch to the fetch, so that the test would pass:

async function fetchPhoto(event) {
  const url = `https://api.unsplash.com/photos/random?query=${event}&per_page=1&client_id=gKEeCzK-8XXRBG8IHbYAGTEUDMN-Dpm9FjxjDS4f2Y0`;

  try {
    const response = await fetch(url);
    const data = await response.json();
    return data;
  } catch (error) {
    console.error('Error fetching photo:', error);
    // Handle the error appropriately, e.g., return a default image or an error message
    return null; 
  }
}

module.exports = { fetchPhoto };

Upvotes: 0

Abdellah Hariti
Abdellah Hariti

Reputation: 707

Response.json() tries to parse the body of the response as JSON, like JSON.parse().

Generally this error means the response you got is not properly formatted JSON. You can inspect it by console.log(), and parsing the body as text using Response.text() first to see what format it has.

Upvotes: 3

Related Questions