Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test axios in Jest?

I have this action in React:

export function fetchPosts() {     const request = axios.get(`${WORDPRESS_URL}`);     return {         type: FETCH_POSTS,         payload: request     } } 

How do I test Axios in this case?

Jest has this use case on their site for asynchronous code where they use a mock function, but can I do this with Axios?

Reference: An Async Example

I have done this so far to test that it is returning the correct type:

it('should dispatch actions with the correct type', () => {     store.dispatch(fetchPosts());     let action = store.getActions();     expect(action[0].type).toBe(FETCH_POSTS); }); 

How can I pass in mock data and test that it returns?

like image 417
Adear Avatar asked Jul 10 '17 15:07

Adear


People also ask

How do I test Axios post in Jest?

To test axios in Jest, we can mock the axios dependency. import * as axios from "axios"; jest. mock("axios"); // ... test("good response", () => { axios.

How do you mock Axios in react native?

Setting up Axios Mock AdapterYou can install it using the command npm install --save-dev axios-mock-adapter . Then, you need to create an Axios instance and pass it to the Axio adapter. import axios, { AxiosRequestConfig } from 'axios'; import AxiosMockAdapter from 'axios-mock-adapter';const axiosMockInstance = axios.


2 Answers

Without using any other libraries:

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({ ... }));   // ... }); 

It is possible to specify the response code:

axios.get.mockImplementation(() => Promise.resolve({ status: 200, data: {...} })); 

It is possible to change the mock based on the parameters:

axios.get.mockImplementation((url) => {     if (url === 'www.example.com') {         return Promise.resolve({ data: {...} });     } else {         //...     } }); 

Jest v23 introduced some syntactic sugar for mocking Promises:

axios.get.mockImplementation(() => Promise.resolve({ data: {...} })); 

It can be simplified to

axios.get.mockResolvedValue({ data: {...} }); 

There is also an equivalent for rejected promises: mockRejectedValue.

Further Reading:

  • Jest mocking documentation
  • A GitHub discussion that explains about the scope of the jest.mock("axios") line.
  • A related question which addresses applying the techniques above to Axios request interceptors.
like image 93
A Jar of Clay Avatar answered Oct 13 '22 00:10

A Jar of Clay


I used axios-mock-adapter. In this case the service is described in ./chatbot. In the mock adapter you specify what to return when the API endpoint is consumed.

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();         });     }); }); 

You can see it the whole example here:

Service: https://github.com/lnolazco/hutoma-test/blob/master/src/services/chatbot.js

Test: https://github.com/lnolazco/hutoma-test/blob/master/src/services/chatbot.test.js

like image 38
Luis Nolazco Avatar answered Oct 13 '22 00:10

Luis Nolazco