samedi 20 février 2021

Test redux actions which uses Redux Thunk and authentication

I am pretty new to testing React-Redux and I would like to test my loadUser-action which uses redux-thunk and calls an end point which has an auth middle ware. Here is code I would like to test:

export const loadUser = () => (dispatch, getState) => {
  dispatch({ type: USER_LOADING });

  axios
    .get('/auth/user', tokenConfig(getState))
    .then((res) =>
      dispatch({
        type: USER_LOADED,
        payload: res.data,
      })
    )
    .catch((err) => {
      console.log(err);
      dispatch({
        type: LOADING_FAILURE,
      });
    });
};

export const tokenConfig = (getState) => {
  const token = getState().auth.token;

  const config = {
    headers: {
      'Content-type': 'application/json',
    },
  };

  if (token) {
    config.headers['x-auth-token'] = token;
  }

  console.log('CONFIG', config);

  return config;
};

And this is my test this far:

import { mockStore } from '../../test/utils/mockStore';
import { USER_LOADED } from '../types/authTypes';
import { loadUser } from './authActions';

describe('loadUser', () => {
  fit('gets user', async () => {
    const store = mockStore();
    const tokenConfig = jest.fn();
    await store.dispatch(loadUser());
    const actions = store.getActions();
    expect(actions[0]).toEqual({ type: USER_LOADED, meta: {} });
  });
});

The tokenConfig function must be called in a different way. I can't figure out how!

Aucun commentaire:

Enregistrer un commentaire