Reputation: 91
I have an action creator, how should i test it with jest ? The problem is , i cant even enter Api function , that is why i cant get LOGIN_SUCCESS, When i check store.getState() it get me only LOGIN_REQUEST and LOGIN_FAILURE
const authUser = (login, password) => async (dispatch) => {
dispatch({
type: actionTypes.LOGIN_REQUEST,
});
try {
return await Api('login', 'post', { login, password })
.then((response) => {
const { data } = response;
if (data.error) {
throw data;
}
const { value } = response.data;
let encoded = [];
encoded = JSON.parse(Base64.decode(value));
dispatch({
type: actionTypes.LOGIN_SUCCESS,
payload: {
encoded,
},
});
return encoded;
})
.catch((error) => {
throw error;
});
} catch (error) {
dispatch({
type: actionTypes.LOGOUT_FAILURE,
payload: {
error,
},
});
}
};
api.js
axios.defaults.withCredentials = true;
const Api = (path, method, data) => {
return axios({
method,
url: `${process.env.REACT_APP_URL}${path}`,
headers: {
Authorization: `Basic ${process.env.REACT_APP_SECRET_TOKEN}`,
'Content-Type': 'application/json;charset=utf-8',
},
data,
});
};
Upvotes: 3
Views: 543
Reputation: 12174
What you have is not an action creator. It's mixed with side effects (i.e api calls). Please consider breaking it into smaller pieces for testing to be more simple and short.
Going back, action creators are simply functions that generates actions.
Like so:
const loginRequest = () => {
type: "LOGIN_REQUEST",
payload: {}
};
const loginSuccess = (encoded) => {
type: "LOGIN_SUCCESS",
payload: {
encoded
}
};
Then to test it is simply:
import { loginRequest, loginSuccess } from "./actions";
it('creates a LOGIN_REQUEST action', () => {
const expectedAction = {
type: 'LOGIN_REQUEST',
}
expect(loginRequest()).toEqual(expectedAction);
});
it('creates a LOGIN_SUCCESS action', () => {
const encoded = 'xxxx';
const expectedAction = {
type: 'LOGIN_SUCCESS',
payload: {
encoded
}
}
expect(loginSuccess(encoded)).toEqual(expectedAction)
});
The goal of testing action creators is to make sure that the generated action is correct / matches what is expected. Testing API calls can be done by mocking or via Redux saga generators.
Upvotes: 3