close

How do I test axios in Jest?

Hello Guys, How are you all? Hope You all Are Fine. Today we are going to learn How do I test axios in Jest? in javascript. So Here I am Explain to you all the possible methods here.

Without wasting your time, Let’s start This Article.

How do I test axios in Jest?

  1. How do I test axios in Jest?

    do I test axios in Jest I've done this with nock, like so:
    import nock from 'nock' import axios from 'axios' import httpAdapter from 'axios/lib/adapters/http' axios.defaults.adapter = httpAdapter describe('foo', () => { it('bar', () => { nock('https://example.com:443') .get('/example') .reply(200, 'some payload') // test... }) })

  2. How do I test axios in Jest?

    do I test axios in Jest I've done this with nock, like so:
    import nock from 'nock' import axios from 'axios' import httpAdapter from 'axios/lib/adapters/http' axios.defaults.adapter = httpAdapter describe('foo', () => { it('bar', () => { nock('https://example.com:443') .get('/example') .reply(200, 'some payload') // test... }) })

Method 1


I could do that following the steps:

  1. Create a folder __mocks__/ (as pointed by @Januartha comment)
  2. Implement an axios.js mock file
  3. Use my implemented module on test

The mock will happen automatically

Example of the mock module:

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

Method 2

I’ve done this with nock, like so:

import nock from 'nock'
import axios from 'axios'
import httpAdapter from 'axios/lib/adapters/http'

axios.defaults.adapter = httpAdapter

describe('foo', () => {
    it('bar', () => {
        nock('https://example.com:443')
            .get('/example')
            .reply(200, 'some payload')

        // test...
    })
})

Summery

It’s all About this article. Hope all method helped you a lot. Comment below Your thoughts and your queries. Also, Comment below which method worked for you? Thank You.

Leave a Comment