reactjs - React Redux 异步 Action 测试

标签 reactjs asynchronous testing redux action

你好,每次我运行测试时,我在测试 react redux async 操作时遇到一些问题,我收到这个数组 [{"type": "LOGIN"}] 而不是这个:

[{"type": "LOGIN"}, {"body": {"data": {"token": "1ca9c02f-d6d2-4eb8-92fd-cec12441f091", "userName": "8888888888888888"}}, "type": "LOGIN_SUCCESS"}]

这是我的代码片段:

Action 代码:

export const LOGIN = 'LOGIN';
export const LOGIN_SUCCESS = 'LOGIN_SUCCESS';
export const LOGIN_ERROR = 'LOGIN_ERROR';

import { Api } from '../../../constants/api';

const api = new Api();

function loginSuccess(data) {
  return {
    type: LOGIN_SUCCESS,
    data,
  };
}

function loginError(error) {
  return {
    type: LOGIN_ERROR,
    error,
  };
}

export function login(fields) {
  return async dispatch => {
    dispatch({ type: LOGIN });
    api
      .register(fields.vin)
      .then(response => {
        const data = Object.assign(response.data, fields);
        return dispatch(loginSuccess(data));
      })
      .catch(error => dispatch(loginError(error)));
  };
}

以及来自 action.test 文件的代码:

import thunk from 'redux-thunk';
import configureMockStore from 'redux-mock-store';
import fetchMock from 'fetch-mock';
import * as actions from './actions';

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

describe('async actions', () => {
  afterEach(() => {
    fetchMock.reset();
    fetchMock.restore();
  });

  it('creates LOGIN_SUCCESS when fetching data has been done', () => {
    fetchMock.getOnce('/register', {
      body: {
        data: {
          userName: '8888888888888888',
          token: '1ca9c02f-d6d2-4eb8-92fd-cec12441f091',
        },
      },
      headers: { 'content-type': 'application/json' },
    });

    const expectedActions = [
      { type: actions.LOGIN },
      {
        type: actions.LOGIN_SUCCESS,
        body: {
          data: {
            userName: '8888888888888888',
            token: '1ca9c02f-d6d2-4eb8-92fd-cec12441f091',
          },
        },
      },
    ];

    const store = mockStore({ data: { id: null, token: null, userName: null } });

    return store.dispatch(actions.login({ id: '8888888888888888' })).then(response => {
      expect(store.getActions()).toEqual(expectedActions);
    });
  });
});

这是第一次测试异步操作,所以我不确定出了什么问题。

最佳答案

您需要返回 API promise,因为您正在解析测试用例中的promise

return store.dispatch(actions.login({ 
      id: '8888888888888888'
})).then(response => {          // resolving Promise here
  expect(store.getActions()).toEqual(expectedActions);
});

你的 Action 必须是这样的

export function login(fields) {
  return dispatch => {              // async is not needed here since no await is used
    dispatch({ type: LOGIN });
    return api                      // return here
      .register(fields.vin)
      .then(response => {
        const data = Object.assign(response.data, fields);
        return dispatch(loginSuccess(data));
      })
      .catch(error => dispatch(loginError(error)));
  };
}

关于reactjs - React Redux 异步 Action 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48378977/

相关文章:

node.js - Node 中的异步函数仅在发送响应后运行

c# - LINQ 代码中的异步 - 说明?

javascript - 异步获取数据,将结果聚合到一个对象。默认情况下,对象是否被 javascript 锁定?

android - 如何以编程方式或使用 Espresso 关闭微调器?

java - 在单元测试中使用 HttpClient 后如何正确清理

javascript - "TypeError: cannot read property ' 原型(prototype) ' of undefined"当 Jest 测试包含 c3 图表的 react 组件时

javascript - 我可以通过 Javascript 在非 React 环境中包含单个 React 组件吗?

javascript - 将事件选项卡事件传递给父组件和同级组件

testing - 依赖按顺序运行的自动化测试可以被认为是不好的做法吗?

reactjs - React Redux 刷新问题