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.
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!
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With