mercredi 30 septembre 2020

What to test and what to ignore in Jest test for a React Redux Action?

I have a Jest test file that tests an action. In the Jest file, I make sure that the action, loadUser(), dispatches all of its expected action types, USER_LOADED and AUTH_ERROR:

  describe('loadUser() action.', () => {
    test('dispatches USER_LOADED.', async () => {
      mockAxios.get.mockImplementationOnce(() =>
        Promise.resolve({
          data: {
            user: {
              name: 'test name',
              email: 'test@test.com',
              avatar: '',
              date: '',
            },
          },
        })
      );

      await store.dispatch(authActions.loadUser());

      const actions = store.getActions();
      const expectedActions = [
        {
          type: USER_LOADED,
          payload: {
            user: {
              name: 'test name',
              email: 'test@test.com',
              avatar: '',
              date: '',
            },
          },
        },
      ];
      expect(actions).toEqual(expectedActions);
    });

    test('dispatches AUTH_ERROR.', async () => {
      mockAxios.get.mockImplementationOnce(() =>
        Promise.reject({ err: 'Failed to load user.' })
      );

      await store.dispatch(authActions.loadUser());

      const actions = store.getActions();
      const expectedActions = [
        {
          type: AUTH_ERROR,
        },
      ];
      expect(actions).toEqual(expectedActions);
    });
  });

However, when I check the coverage report, the action's Branch coverage is not 100%. The following is the action file and action in question:

export const loadUser = () => async (dispatch) => {
  // This branch is not being tested. Should it be tested in my actions test?
  if (localStorage.token) {
    setAuthToken(localStorage.token);
  }

  try {
    const res = await axios.get('/api/auth');

    dispatch({
      type: USER_LOADED,
      payload: res.data,
    });
  } catch (err) {
    dispatch({
      type: AUTH_ERROR,
    });
  }
};

Should I be testing the branch if (localStorage.token) {} in my actions Jest test? If so, how should I test it? My current assumption is that my Redux action tests should make sure the correct action types are dispatched.

If I don't need to test that branch, is it fine to leave my coverage for branch at 50%?

Aucun commentaire:

Enregistrer un commentaire