reactjs - 使用 Redux Thunk 和 Axios 测试 Action Creator

标签 reactjs redux axios chai redux-thunk

我有一个 redux-thunk 操作创建器,它通过 axios 发出 API 请求,然后该请求的结果决定将哪种操作分派(dispatch)到我的 reducer (AUTH 或 UNAUTH)。

这工作得很好,但我不确定测试此功能的正确方法是什么。我已经找到了下面的解决方案,但在测试中出现以下错误:

1) AUTH ACTION
   returns a token on success:
     TypeError: Cannot read property 'then' of undefined

现在这个错误让我相信我真正从 Action 创建者那里得到的并不是 promise ,而是我真的在努力寻找前进的方向。

src/actions/index.js

import axios from "axios";

import { AUTH_USER } from "./types";

const ROOT_URL = "http://localhost:";
const PORT = "3030";

export function signinUser({ email, password }) {
  return ((dispatch) => {
    axios
      .post(`${ROOT_URL}${PORT}/signin`, { email, password })
      .then(response => {
        // update state to be auth'd
        dispatch({ type: AUTH_USER });
        // Save token locally
        localStorage.setItem('token', response.data.token)
      })
      .catch(error => {
        dispatch({ type: AUTH_ERROR, payload: error });
      });
  });
}

测试/actions/index_test.js

import { expect } from "../test_helper";
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
import moxios from 'moxios';

import { AUTH_USER } from "../../src/actions/types";

import { signinUser } from "../../src/actions/index";

const middleware = [thunk];
const mockStore = configureMockStore(middleware);
let store;
let url;

describe('AUTH ACTION', () => {
  beforeEach(() => {
    moxios.install();
    store = mockStore({});
    url = "http://localhost:3030";
  });
  afterEach(() => {
    moxios.uninstall();
  });

  it('returns a token on success', (done) => {
    moxios.stubRequest(url, {
      status: 200,
      response: {
        data: {
          token: 'sample_token'
        }
      },
    });

    const expectedAction = { type: AUTH_USER }

    let testData = { email: "<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1d69786e692c5d69786e69337e7270" rel="noreferrer noopener nofollow">[email protected]</a>", password: "1234"}
    store.dispatch(signinUser(testData)).then(() => {
      const actualAction = store.getActions()
      expect(actualAction).to.eql(expectedAction)
    })
  })
})

任何帮助或见解将不胜感激。

最佳答案

store.dispatch(someThunk()).then() 仅当 thunk 返回 Promise 时才有效,并且您的 thunk 实际上并未返回 Promise。

如果您只是将 return 放在 axios() 前面,它应该可以工作。

关于reactjs - 使用 Redux Thunk 和 Axios 测试 Action Creator,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49882413/

相关文章:

javascript - 无法访问数据请求 Axios、React-Redux

javascript - 来自本地 PHP 的 Axios GET 只是返回代码而不是执行

reactjs - 允许 antd 上传组件显示进度条,然后在上传后删除项目

node.js - 将 axios 与 async 和 await 结合使用

javascript - React 父函数调用子函数的嵌套 componentDidMount 函数?

reactjs - 组件未更新深度嵌套的 redux 对象

redux - 如何在 Redux-orm 中将 API 响应映射到数据库状态

javascript - react +redux : state of store changed without view changing

reactjs - 如何为 React 组件参数创建文字类型?

javascript - 在 React Native 中停止顺序动画