Skip to content

how to test api calls using fetch? #967

Closed
@bondarewicz

Description

@bondarewicz

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions