Cómo realizar pruebas unitarias de llamadas a la API con merocked fetch() en react-native con Jest


En React Native uso fetch para realizar peticiones de red, sin embargo fetch no es un módulo explícitamente requerido, por lo que es aparentemente imposible burlarse en Broma.

Incluso intentar llamar a un método que usa fetch en una prueba resultará en:

ReferenceError: fetch no está definido

¿Hay alguna forma de probar tales solicitudes de API en react native con Jest?

Author: Ronan Boiteau, 2016-03-17

5 answers

Dentro de su caso de prueba, puede burlarse de cualquier función que desee utilizando las burlas de Jest:

fetch = jest.fn(() => new Promise(resolve => resolve()));

Este enfoque solo funciona para los casos de prueba basados en promesas (ver pit en los documentos de Jest).

En cuanto a que fetch es una función asincrónica, debe ejecutar todas sus pruebas usando pit (lea más sobre las pruebas asincrónicas aquí).

 19
Author: Alexey Kureev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-17 20:48:18

En lugar de rodar su propio mock, puede usar el paquete jest-fetch-mock npm para anular el objeto global fetch. Ese paquete le permite configurar respuestas falsas y verificar las solicitudes enviadas. Consulte ese enlace para obtener ejemplos de uso extensos.

 7
Author: ArthurDenture,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-12-07 18:47:49

Otro enfoque donde te burlas del objeto global fetch:

const mockSuccesfulResponse = (
  status = 200,
  method = RequestType.GET,
  returnBody?: object
) => {
  global.fetch = jest.fn().mockImplementationOnce(() => {
    return new Promise((resolve, reject) => {
      resolve({
        ok: true,
        status,
        json: () => {
          return returnBody ? returnBody : {};
        },
      });
    });
  });
};

El método de ayuda anterior se puede modificar de la manera que desee: -) Espero que ayude a alguien

 3
Author: jhm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-04 14:08:28

Resolví esto agregando isomorphic-fetch.

$ npm install --save isomorphic-fetch

Y usándolo como

import fetch from 'isomorphic-fetch';
...
fetch('http://foo.com');

Whatwg-fetch podría funcionar también

 1
Author: Harry Moreno,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-15 15:48:55

Como @ ArthurDenture recomendó, puedes usar fetch-mock , pero hay algunos paquetes adicionales que necesitarás instalar para que funcione con React Native y Jest:

$ npm install --save-dev fetch-mock
$ npm install --save-dev babel-plugin-transform-runtime
$ npm install --save-dev babel-preset-env

Luego puede simular las solicitudes de recuperación en sus pruebas. He aquí un ejemplo:

// __tests__/App.test.js
import React from 'react';
import App from '../App';
import fetchMock from 'fetch-mock';
import renderer from 'react-test-renderer';

it('renders without crashing', () => {
  fetchMock.mock('*', 'Hello World!');
  const rendered = renderer.create(<App />).toJSON();
  expect(rendered).toBeTruthy();
});
 0
Author: Tom Aranda,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-06-08 22:46:06