Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to really call fetch in Jest test

Is there a way to call fetch in a Jest test? I just want to call the live API to make sure it is still working. If there are 500 errors or the data is not what I expect than the test should report that.

I noticed that using request from the http module doesn't work. Calling fetch, like I normally do in the code that is not for testing, will give an error: Timeout - Async callback was not invoked within the 5000ms timeout specified by jest.setTimeout. The API returns in less than a second when I call it in the browser. I use approximately the following to conduct the test but I also have simply returned the fetch function from within the test without using done with a similar lack of success:

import { JestEnvironment } from "@jest/environment";
import 'isomorphic-fetch';
import { request, } from "http";
jest.mock('../MY-API');

describe('tests of score structuring and display', () => {
    test('call API - happy path', (done) => {
        fetch(API).then(
            res => res.json()
        ).then(res => {
            expect(Array.isArray(response)).toBe(true);
            console.log(`success: ${success}`);
            done();
        }).catch(reason => {
            console.log(`reason: ${reason}`);
            expect(reason).not.toBeTruthy();
            done();
        });
    });
});

Oddly, there is an error message I can see as a console message after the timeout is reached: reason: ReferenceError: XMLHttpRequest is not defined

How can I make an actual, not a mocked, call to a live API in a Jest test? Is that simply prohibited? I don't see why this would fail given the documentation so I suspect there is something that is implicitly imported in React-Native that must be explicitly imported in a Jest test to make the fetch or request function work.

like image 748
haleonj Avatar asked Apr 03 '19 15:04

haleonj


1 Answers

Putting aside any discussion about whether making actual network calls in unit tests is best practice...

There's no reason why you couldn't do it.

Here is a simple working example that pulls data from JSONPlaceholder:

import 'isomorphic-fetch';

test('real fetch call', async () => {
  const res = await fetch('https://jsonplaceholder.typicode.com/users/1');
  const result = await res.json();
  expect(result.name).toBe('Leanne Graham');  // Success!
});

With all the work Jest does behind the scenes (defines globals like describe, beforeAll, test, etc., routes code files to transpilers, handles module caching and mocking, etc.) ultimately the actual tests are just JavaScript code and Jest just runs whatever JavaScript code it finds, so there really aren't any limitations on what you can run within your unit tests.

like image 144
Brian Adams Avatar answered Sep 28 '22 08:09

Brian Adams