用jest测试redux异步动作创建者

时间:2017-11-14 11:48:27

标签: redux async-await axios jest nock

我开始为我的应用程序编写测试。我正在尝试为redux异步创建者创建测试。

问题是当我运行测试时出现以下错误:

获取所有用户>调度操作loadUsersSuccess

操作可能没有未定义的"类型"属性。你拼错了吗?行动:未定义

所有动作都定义了类型常量,所以我不明白应该是什么问题。

const LOAD_ALL_USERS_SUCCESS = "src/containers/User/LOAD_ALL_USERS_SUCCESS";
const LOAD_ALL_USERS_FAILURE = "src/containers/User/LOAD_ALL_USERS_FAILURE";

//action creators
    export function loadUsersSuccess(users) {
      return {
        type: LOAD_ALL_USERS_SUCCESS,
        payload: users
      };
    }

    export function loadUsersFailure(error) {
      return {
        type: LOAD_ALL_USERS_FAILURE,
        payload: error
      };
    }
import nock from "nock";
import { loadUsersSuccess, loadUsersFailure } from "./ducks";
import configureStore from "redux-mock-store";

const middlewares = [];

const mockStore = configureStore(middlewares);

const LOAD_ALL_USERS_SUCCESS = "src/containers/User/LOAD_ALL_USERS_SUCCESS";
const LOAD_ALL_USERS_FAILURE = "src/containers/User/LOAD_ALL_USERS_FAILURE";

const users = [
  {
    first_name: "Emlynne",
    last_name: "Spellacy",
    email: "espellacy0@lycos.com",
    gender: "Female",
    age: 1965,
    country: "Indonesia"
  },
  {
    first_name: "Alie",
    last_name: "Dalrymple",
    email: "adalrymple1@telegraph.co.uk",
    gender: "Female",
    age: 1976,
    country: "Pakistan"
  }
];

function fetchData() {
  return async (dispatch) => {
    try {
      const { data } = await axios.get("/users");
      dispatch(loadUsersSuccess(data));
    } catch (error) {
      dispatch(loadUsersFailure(error));
    }
  };
}

describe("Fetch all users", () => {
  afterEach(() => {
    nock.cleanAll()
  })
  test("Should load all Users", () => {
    nock("http://localhost:8000")
      .get("api/users")
      .reply(200, users);

    const expectedAction = [
      {
        type: LOAD_ALL_USERS_SUCCESS,
        payload: users
      },
      {
        type: LOAD_ALL_USERS_FAILURE,
        payload: "error"
      }
    ];
    const store = mockStore({});

    return store.dispatch(fetchData()).then(() => {
      expect(store.getActions()).toEqual(expectedAction);
    });
  });
});

1 个答案:

答案 0 :(得分:1)

问题在于调度功能不存在。所以,我需要添加以下几行。

import thunk from "redux-thunk";

const middlewares = [thunk];