question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

how to test api calls using fetch?

See original GitHub issue

I’m having a hard time understanding below behaviour and would appreciate any help to pointing me into the right direction.

I have a generic class for my api calls:

class Api {
 static ack(param1, param2) {
  return fetch(process.env.REACT_APP_ACK_URL + param1 + '/' + param2, {
          method: 'PUT',
          headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
          }
        })
        .then((response) => {
          if(response.ok) {
            return response.json();
          } else {
            console.log('ack failed', response.statusText)
          }
        })
        .catch((ex) => {
          throw new Error('fetch failed' + ex)
        });
 }
}

in my Api.test.js I have a following code

import Api from './Api';

describe("Api", function () {

  beforeEach(function() {
    window.fetch = jest.fn().mockImplementation(() => Promise.resolve({ok: true, Id: '123'}));
  });

  it("ack", function () {

    Api.ack('foo', 'bar').then(response => {
      console.log(response); //< this is never printed
      expect(response.Id).toBe(1); //< always pass / gets ignored?
    });

  });
});

regardless of what I set the response.Id in Promise.resolve({ok: true, Id: '123'})

expect(response.Id).toBe(1) or expect(response.Id).toBe('abc') always pass

Issue Analytics

  • State:closed
  • Created 7 years ago
  • Reactions:19
  • Comments:11 (4 by maintainers)

github_iconTop GitHub Comments

50reactions
bondarewiczcommented, Oct 26, 2016

@gaearon you rock dude, thanks so much 😃 I ended up changing the mockImplementation as per below and using async/await

Api.test.js

beforeEach(function() {

  global.fetch = jest.fn().mockImplementation(() => {
      var p = new Promise((resolve, reject) => {
        resolve({
          ok: true, 
          Id: '123', 
          json: function() { 
            return {Id: '123'}
          }
        });
      });

      return p;
  });

});


it("ack", async function() {
  const response = await Api.ack('foo', 'bar');
  console.log(response);
  expect(response.Id).toBe(1); 
});

results in :

expect(received).toBe(expected)

Expected value to be (using ===):
  1
Received:
  "123"

Difference:

Comparing two different types of values:
  Expected: number
  Received: string

can this be considered as good practice for testing promises returned by fetch in jest?

41reactions
gaearoncommented, Oct 26, 2016

By the way I noticed you don’t return Promise from the test. The runner can’t know to wait for the promise to finish in this case.

Have you tried returning Promise or using async await? See the async tutorial.

  it("ack", async function () {
    const response = await Api.ack('foo', 'bar');
    console.log(response);
    expect(response.Id).toBe(1);
  });
Read more comments on GitHub >

github_iconTop Results From Across the Web

Using the Fetch API - MDN Web Docs
The Fetch API provides a JavaScript interface for accessing and manipulating parts of the protocol, such as requests and responses.
Read more >
Using and Testing the Fetch API - DEV Community ‍ ‍
Displaying all GoT books. This guide is about writing code that uses the Fetch API in React and TypeScript and how to write...
Read more >
Fetch API – How to Make a GET Request and POST Request ...
fetch () is a mechanism that lets you make simple AJAX (Asynchronous JavaScript and XML) calls with JavaScript. Asynchronous means that you can ......
Read more >
Learn to use fetch() in API call Easily ! - CODERSERA
Today we are going to explore the fetch function in API calls and get to know about different methods (such as GET, POST,...
Read more >
How To Mock Fetch in Jest | Leigh Halliday
Making HTTP requests in tests isn't a great idea in most situations... it can slow your tests down, is unreliable, and the API...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found