【问题标题】:testing redux async action creators with jest用 jest 测试 redux 异步动作创建者
【发布时间】:2018-04-27 08:37:19
【问题描述】:

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

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

获取所有用户 › dispatch action 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);
    });
  });
});

【问题讨论】:

    标签: redux async-await axios jestjs nock


    【解决方案1】:

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

    import thunk from "redux-thunk";
    
    const middlewares = [thunk];
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 2016-09-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多