Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Write a jest test by mocking Axios, using the action provided?

I am new to testing using jest and I am stuck on how I can test this piece of code given to show that Axios.post is called when my registerUser is called. I have searched online and don't have a solid solution to post. Would be grateful if a solution could be provided

This is the function I need to test from authAction.js

export const registerUser = (userData, history) => dispatch => {
  axios
    .post("/api/users/register", userData)
    .then(res => history.push("/login")) // re-direct to login on successful register
    .catch(err =>
      dispatch({
        type: GET_ERRORS,
        payload: err.response.data
      })
    );
};

I have tried this but it doesn't seem to work.

import * as authActions from './authActions';
import axios from 'axios';
import configureStore from 'redux-mock-store'; //ES6 modules
import thunk from 'redux-thunk';
const middleware = [thunk];
const mockStore = configureStore(middleware);


describe('test register user axios', () => {
    it('should give a response of 201 back after it registers user', () => {


        var userData = {email: "[email protected]",
        name: "Kris Kamara",
        password: "adam123",
        password2: "adam123"
        }

        var history = jest.fn();

        const initialState = {}
        const store = mockStore(initialState)

        store.dispatch(authActions.registerUser({userData}, history));
        expect(axios).toHaveBeenCalledTimes(1);

    });
  });

Thanks in advance.

like image 340
Aaron Chatrath Avatar asked Dec 09 '25 09:12

Aaron Chatrath


1 Answers

Return the Promise from the function like this:

export const registerUser = (userData, history) => dispatch => {
  return axios  // <= return the Promise
    .post("/api/users/register", userData)
    .then(res => history.push("/login")) // re-direct to login on successful register
    .catch(err =>
      dispatch({
        type: GET_ERRORS,
        payload: err.response.data
      })
    );
};

...and then you can test it like this:

import * as authActions from './authActions';
import axios from 'axios';

describe('registerUser', () => {

  let mock;
  beforeEach(() => {
    mock = jest.spyOn(axios, 'post');
  });
  afterEach(() => {
    mock.mockRestore();
  });

  it('should register the user and redirect to login', async () => {
    const push = jest.fn();
    const history = { push };
    const dispatch = jest.fn();
    mock.mockResolvedValue();  // mock axios.post to resolve

    await authActions.registerUser('the user data', history)(dispatch);

    expect(mock).toHaveBeenCalledWith('/api/users/register', 'the user data');  // Success!
    expect(history.push).toHaveBeenCalledWith('/login');  // Success!
  });
});
like image 56
Brian Adams Avatar answered Dec 11 '25 20:12

Brian Adams



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!