lundi 1 avril 2019

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: "kamara@fc.come",
        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.

Aucun commentaire:

Enregistrer un commentaire