Testing Redux Login Action

I hope I can ask for some help on how to test the Redux action, which includes calling the login API. I looked at several examples of testing asynchronous actions, but I did not think about how to check the code below.

As a starting point, I would like to verify that a) AUTH_USERis called if the request .postreturns 200 and b)localStorage` that contains the token from the API call.

I looked at using redux-mock-store, fetch-mockand isomorphic-fetchto mock API calls, to always get the expected API response, but I have no idea where to start with the test.

Any help would be greatly appreciated at the starting point of the tests! Even some help in just checking that he 200will return AUTH_USERwill be appreciated!

Note. In other places for other tests I use, redux-poppy-shop, enzyme, chai, expect, fetch-mock, isomorphic-fetch

import axios from 'axios';
import { browserHistory } from 'react-router';
import { API_URL } from 'config';
import {
  AUTH_USER
} from './types';

export function loginUser({ email, password }) {
  return function (dispatch) {
    axios.post(`${API_URL}/auth/login`, { email, password })
      .then((response) => {
        dispatch({ type: AUTH_USER });
        localStorage.setItem('token', response.data.token);
        browserHistory.push('/feature');
      })
      .catch(() => {
        dispatch(authError('Bad Login Info'));
      });
  };
}
+4
source share
1 answer

Asynchronous Test Motivation

We want to ensure that the AUTHENTICATION_SUCCESS action is dispatched by our redux thunk middleware if the AUTHENTICATION_FAILED action is performed upon successful login if the login error is completed.

, Redux Thunk, Thunk Action.

Action Redux Thunk, API

  • mock- unit test redux-thunk
  • , ​​ , HTTP-, , . -, http-, .
  • , HTTP.

nock, api .

import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import nock from 'nock'
import expect from 'expect' // You can use any testing library

// modify these imports to suit your project
import * as actions from '../../actions/TodoActions' 
import * as types from '../../constants/ActionTypes'

import {
  AUTH_USER, AUTH_ERROR
} from './types';

const API_URL = 'www.api-example.com'
const middlewares = [ thunk ]
const mockStore = configureMockStore(middlewares)

describe('async actions', () => {
  afterEach(() => {
    nock.cleanAll()
  })

  it('creates AUTH_USER action when user is logged in', () => {
    nock(API_URL)
      .post(/auth/login)
      .reply(200, { data: 'Logged in successfully'] }})

    const expectedActions = [
      { type: AUTH_USER }
    ]
    const store = mockStore({ })

    return store.dispatch(actions.loginUser({'example@x.com','password'}))
      .then(() => { // return of async actions
        expect(store.getActions()).toEqual(expectedActions)
      })
  })

  it('creates AUTH_ERROR if user login fails', () => {
    nock(API_URL)
      .post(/auth/login)
      .reply(404, { data: {error: 404 }] }})

    const expectedActions = [
      { type: AUTH_ERROR }
    ]
    const store = mockStore({ })

    return store.dispatch(actions.loginUser({'example@x.com','password'}))
      .then(() => { // return of async actions
        expect(store.getActions()).toEqual(expectedActions)
      })
  })
})

, , return , thunk.

, , axios.post, .then , , , .

Thunk

import axios from 'axios';
import { browserHistory } from 'react-router';
import { API_URL } from 'config';
import {
  AUTH_USER
} from './types';

export function loginUser({ email, password }) {
  return function (dispatch) {
    return axios.post(`${API_URL}/auth/login`, { email, password })
      .then((response) => {
        dispatch({ type: AUTH_USER });
        localStorage.setItem('token', response.data.token);
        browserHistory.push('/feature');
      })
      .catch(() => {
        dispatch(authError('Bad Login Info'));
      });
  };
}
+2

Source: https://habr.com/ru/post/1664158/


All Articles