0

I am currently realized I shouldn't be calling api straight through network request while using jestjs to check for api.

I have been looking at some posts + youtube tutorials such as https://www.leighhalliday.com/mocking-axios-in-jest-testing-async-functions Mock inner axios.create() but still a bit confused and now sure how to get this to work.

I created a registration api and wanted to do test on it, and after reading the mockup documentation and so on. I have something like...this as my folder structure

folder structure

this is how my base_axios/index.js looks like, BASE_URL is just something like http://localhost:3000

const axios = require('axios');

const { BASE_URL } = require('../base');

const baseOption = {
    // without adding this, will not be able to get axios response status
    validateStatus: function (status) {
        return status >= 200 && status <= 503;
    },
    baseURL: BASE_URL,
    headers: { 'Content-Type': 'application/json' },
};

module.exports = axios.create(baseOption);

apis/auth.js

const request = require('./base_axios');

module.exports = {
    register: data => request.post('/auth/register', data),
};

mocks/axios.js

const mockAxios = jest.genMockFromModule('axios');

mockAxios.create = jest.fn(() => mockAxios);

module.exports = mockAxios;

routes/auth/register.js

const Auth = require('../../apis/auth');
const mockAxios = require('axios');

    test('calls axios for registration', async () => {
        // this should give me an error and show which api has been called
        expect(mockAxios.post).toHaveBeenCalledWith('what is the api');

        const response = await Auth.register();
        console.log(response, 'response'); // response here gives me undefined
    });

I am not getting which api call is being called and te response gives me undefined also getting this error from jest expect(jest.fn()).toHaveBeenCalledWith(...expected)

Thanks in advance for anyone with advice and suggestions.

PS

jest.config.js

module.exports = {
  clearMocks: true,
  coverageDirectory: "coverage",

  // The test environment that will be used for testing
  testEnvironment: "node",
};
Dora
  • 6,776
  • 14
  • 51
  • 99
  • Can you please add jest config file, want to check value for roots directory as specified here https://jestjs.io/docs/en/configuration#roots-arraystring – Sanket Phansekar Jan 02 '20 at 05:46
  • @SanketPhansekar I do have a `jest.config.js` I edited my post – Dora Jan 02 '20 at 09:06
  • `const response = await Auth.register();` will of course return undefined since it doesn't return anything. try returning the Promise from `request.post('/auth/register', data)` – fubar Jan 02 '20 at 09:19
  • @fubar still nothing though. – Dora Jan 14 '20 at 18:49

1 Answers1

0

You can mock axios and an implemtation for it as below:

jest.spyOn(axios, 'post').mockImplementation();

For an example:

test('calls axios for registration', async () => {
const mockDataRequest = {};
const mockPostSpy = jest
    .spyOn(axios, 'post')
    .mockImplementation(() => {
        return new Promise((resolve) => {
            return resolve({
                data: {},
            });
        });
    });

expect(mockPostSpy).toHaveBeenCalledTimes(1);

expect(mockPostSpy).toBeCalledWith(
    `/auth/register`,
    expect.objectContaining(mockDataRequest)
);

});

Hieu Dang
  • 343
  • 3
  • 11