Tengo esta acción en React:
export function fetchPosts() { const request = axios.get(`${WORDPRESS_URL}`); return { type: FETCH_POSTS, payload: request } }¿Cómo pruebo Axios en este caso?
Jest tiene este caso de uso en su sitio para código asíncrono donde usan una función simulada, pero ¿puedo hacer esto con Axios?
Referencia: un ejemplo asíncrono
He hecho esto hasta ahora para probar que está devolviendo el tipo correcto:
it('should dispatch actions with the correct type', () => { store.dispatch(fetchPosts()); let action = store.getActions(); expect(action[0].type).toBe(FETCH_POSTS); });¿Cómo puedo pasar datos simulados y probar que devuelven?
Sin usar ninguna otra biblioteca:
import * as axios from "axios"; // Mock out all top level functions, such as get, put, delete and post: jest.mock("axios"); // ... test("good response", () => { axios.get.mockImplementation(() => Promise.resolve({ data: {...} })); // ... }); test("bad response", () => { axios.get.mockImplementation(() => Promise.reject({ ... })); // ... });Es posible especificar el código de respuesta:
axios.get.mockImplementation(() => Promise.resolve({ status: 200, data: {...} }));Es posible cambiar el simulacro en función de los parámetros:
axios.get.mockImplementation((url) => { if (url === 'www.example.com') { return Promise.resolve({ data: {...} }); } else { //... } });Jest v23 introdujo algo de azúcar sintáctico para burlarse de Promises:
axios.get.mockImplementation(() => Promise.resolve({ data: {...} }));Se puede simplificar a
axios.get.mockResolvedValue({ data: {...} }); También hay un equivalente para las promesas rechazadas: mockRejectedValue .
Otras lecturas:
jest.mock("axios") .Usé axios-mock-adapter . En este caso el servicio se describe en ./chatbot. En el adaptador simulado, especifica qué devolver cuando se consume el punto final de la API.
import axios from 'axios'; import MockAdapter from 'axios-mock-adapter'; import chatbot from './chatbot'; describe('Chatbot', () => { it('returns data when sendMessage is called', done => { var mock = new MockAdapter(axios); const data = { response: true }; mock.onGet('https://us-central1-hutoma-backend.cloudfunctions.net/chat').reply(200, data); chatbot.sendMessage(0, 'any').then(response => { expect(response).toEqual(data); done(); }); }); });Puedes verlo todo el ejemplo aquí:
Servicio: https://github.com/lnolazco/hutoma-test/blob/master/src/services/chatbot.js
Prueba: https://github.com/lnolazco/hutoma-test/blob/master/src/services/chatbot.test.js
Podría hacerlo siguiendo los pasos:
axios.jsEl simulacro sucederá automáticamente.
Ejemplo del módulo simulado:
module.exports = { get: jest.fn((url) => { if (url === '/something') { return Promise.resolve({ data: 'data' }); } }), post: jest.fn((url) => { if (url === '/something') { return Promise.resolve({ data: 'data' }); } if (url === '/something2') { return Promise.resolve({ data: 'data2' }); } }), create: jest.fn(function () { return this; }) };