【问题标题】:React-Redux component test fails when using async actions使用异步操作时 React-Redux 组件测试失败
【发布时间】:2018-05-05 13:25:32
【问题描述】:

我正在尝试测试 react-redux 连接的应用程序,该应用程序具有 aync 操作以从 API 获取数据。但是由于某种原因测试失败了。我在这里做错了什么?

AssertionError: 预期 { length: 0 } 的长度为 1 但得到了 0

posts.js(Redux Action)

import instance from "./../config/axiosconfig";

export const postList = () => {
  return dispatch => {
    return instance.get("/posts")
      .then(res => {
        const posts = res.data;
        return dispatch({
          type: "POST_LIST", posts
        });
      });
  };
};

posts.js(反应组件)

import React, { Component } from "react";
import { connect } from "react-redux";
import {postList} from "../actions/posts";
import PropTypes from "prop-types";

class Post extends Component {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    if (this.props.posts === undefined || this.props.posts.length === 0) {
      const {dispatch} = this.props;
      dispatch(postList());
    }
  }
  render() {
    let postLists = "";
    if (this.props.posts) {
      postLists = this.props.posts.map((list, i) => (
                    <li key = {i}>
                      {list.title}
                    </li>
                  ));
    }
    return (
      <div>
        <h2>About</h2>
        <p>Services</p>
        <ol className="post-list">
          {postLists}
        </ol>
      </div>
    );
  }
}
Post.propTypes = {
  posts: PropTypes.array,
  dispatch: PropTypes.func
};
const mapDispatchToProps = (dispatch) => ({ dispatch });

const mapStateToProps = (state) => {
  return { posts: state.PostReducer ? state.PostReducer.posts : [] };
};

export default connect(mapStateToProps, mapDispatchToProps)(Post);

Post.test.js(组件测试)

import React from "react";
import Post from "client/components/post";
import { Provider } from 'react-redux';
import PostReducer from "client/reducers/posts";
import {mount, render, shallow} from 'enzyme'
import instance from "client/config/axiosconfig";
import { expect } from "chai";
import moxios from "moxios";
import { createStore, applyMiddleware, combineReducers } from 'redux';
import configureStore from "redux-mock-store";
import thunkMiddleware from "redux-thunk";
let store;
let wrapper;

describe("Post Component", () => {

    beforeEach(() => {
        moxios.install(instance);
    });

    afterEach(() => {
        moxios.uninstall(instance);
    });

    it("has expected posts lists listed", async () => {
        store = setupStore();
        const payload = [{
            body: "TEST",
            id: 1,
            title: "Test Title"
        }];
        moxios.wait(() => {
            const request = moxios.requests.mostRecent();
            request.respondWith({
                status: 200,
                response: payload
            });
        });
        wrapper = mount(<Provider store={store}><Post/></Provider>);
        expect(wrapper.find('.post-list li')).to.have.length(1);  
    });

    function setupStore() {
        return createStore(
          combineReducers({ PostReducer }),
          applyMiddleware(thunkMiddleware)
        );
    }
});

【问题讨论】:

    标签: reactjs redux mocha.js


    【解决方案1】:

    在做出断言时,您已存根的请求可能仍处于未决状态。

    尝试以下方法:

    it("has expected posts lists listed", async () => {
        store = setupStore();
        const payload = [{
            body: "TEST",
            id: 1,
            title: "Test Title"
        }];
    
        const promise = moxios.wait(() => {
            const request = moxios.requests.mostRecent();
            request.respondWith({
                status: 200,
                response: payload
            });
        });
    
        const wrapper = mount(<Provider store={store}><Post/></Provider>);
    
        await promise;
    
        wrapper.update(); // May not be necessary
    
        expect(wrapper.find('.post-list li')).to.have.length(1);
    });
    

    【讨论】:

    • 我按照你的解释试过了。但仍然出现同样的错误
    猜你喜欢
    • 2021-04-03
    • 1970-01-01
    • 2017-03-03
    • 2019-10-31
    • 2017-10-14
    • 2017-01-26
    • 2019-11-12
    • 2017-03-04
    相关资源
    最近更新 更多