用 jest 测试 redux 异步动作创建者
Posted
技术标签:
【中文标题】用 jest 测试 redux 异步动作创建者【英文标题】:testing redux async action creators with jest 【发布时间】: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);
);
);
);
【问题讨论】:
【参考方案1】:问题是调度功能不存在。所以,我需要添加以下几行。
import thunk from "redux-thunk";
const middlewares = [thunk];
【讨论】:
以上是关于用 jest 测试 redux 异步动作创建者的主要内容,如果未能解决你的问题,请参考以下文章
Redux-Thunk - 异步动作创建者承诺和链接不起作用
在未弹出 Redux 的情况下测试 Jest React-Native Expo CRNA