【问题标题】:How to stub async action in componentDidMount for react redux connected component test using Jest如何在componentDidMount中存根异步操作以使用Jest进行react redux连接组件测试
【发布时间】:2019-05-14 23:11:54
【问题描述】:

我有一个简单的连接组件,在加载时,它通过调用异步操作来构建用户详细信息,然后从状态中显示这些详细信息。

import PropTypes from 'prop-types';
import React from 'react';
import { connect } from 'react-redux';
import { loadUserDetails } from '../actions/user';

class ShowUserDetailsLite extends React.Component {
  componentDidMount() {
    this.props.loadUserDetails();
  }

  render() {
    const { userDetails } = this.props;

    const handleClickEdit = () => {
      history.push(editProfilePath());
    };

    return (
      <div>
        <div className="email">
          {userDetails.email_address}
        </div>
        <div className="name">
          {userDetails.first_name} {userDetails.last_name}
        </div>
      </div>
    );
  }
}

ShowUserDetailsLite.propTypes = {
  loadUserDetails: PropTypes.func.isRequired,
  userDetails: PropTypes.shape({}).isRequired,
};

const mapDispatchToProps = {
  loadUserDetails,
};

function mapStateToProps(state) {
  const userDetails = state.user.details;
  return { userDetails };
}

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

首先,我想测试我的组件是否显示了正确的状态信息,所以我进行了以下测试。

import configureStore from 'redux-mock-store'
import { shallow } from 'enzyme';
import { expect } from 'chai';
import React from 'react'
import Provider from 'react-redux';
import ShowUserDetailsLite from '../../components/ShowUserDetailsLite'

describe('ShowUserDetailsLite component', () => {
  it('displays the current user', () => {
    const mockStore = configureStore();
    let store = mockStore({
      user: {
        details: {
          email_address: 'test@test.com',
          first_name: 'First',
          last_name: 'Last',
        }
      },
    });
    let wrapper = shallow(<ShowUserDetailsLite store={store} loadUserDetails={jest.fn()}/>).dive()
    expect(wrapper.find('.email').text()).to.eql('test@test.com')
  })
})

当我使用注释掉的 componentDidMount 函数运行此测试时,它运行良好,读取状态并显示正确的信息,但是当我运行包含 componentDidMount 函数的测试时,测试尝试调用该函数我收到以下错误:

 FAIL  app/tests/components/ShowUserDetailsLite.test.js
  ShowUserDetailsLite component
    ✕ displays the current user (32ms)

  ● ShowUserDetailsLite component › displays the current user

    ReferenceError: regeneratorRuntime is not defined

      16 |
      17 | export function loadUserDetails() {
    > 18 |   return async dispatch => {
         |   ^
      19 |     try {
      20 |       const res = await axios.get(`/${window.realm}/api/userDetails`);
      21 |       dispatch({ type: SET_USER_DETAILS, data: res.data });

在这个阶段,我不关心测试 loadUserDetails 函数,所以我只想存根它。我知道要做到这一点,您只需将函数作为属性传递,我试图通过传递一个 jest 函数来做到这一点:

let wrapper = shallow(<ShowUserDetailsLite store={store} loadUserDetails={jest.fn()}/>).dive()

但我仍然收到错误消息。如何正确存根在 componentdidmount 中调用的异步操作以进行连接组件测试?

【问题讨论】:

    标签: javascript reactjs redux jestjs


    【解决方案1】:

    我可能来晚了,但我最终在这里也遇到了同样的问题,在挖掘了 2 天后,我发现了:

    由于您使用 Connect 包装您的组件,您需要将您的存根 props 函数传递给子组件

    您可以在没有 HOC 连接的情况下导出组件

    export ShowUserDetailsLite 
    

    然后导入

    import {ShowUserDetailsLite} from ...
    

    现在你有了一个没有连接的浅化组件,你可以直接传递像 users 和模拟的 loadUserDetails 这样的道具

    为了更完整的原始问题:

    如何存根 componentDidMount

    当您 mountshallow 您的组件时,您将触发 componentDidMount 。

    浅浅

    对于shallow 渲染,您可以使用选项{disableLifecycleMethods:true}

     wrapper = shallow(
              <Stats {...props} />, {disableLifecycleMethods:true}
            )
    

    带支架

    如果您想使用mount 进行渲染,您需要以这种方式存根componentDidMount:

    jest.spyOn(YOUCOMPONENT.prototype, 'componentDidMount').mockImplementation();
    

    然后你挂载你的组件

    wrapper = mount(
          <Stats {...props} />
        )
    

    如果你想存根在 componentDidMount 中调用的方法,现在你可以访问这些方法:

    const spy = jest.spyOn(wrapper.instance(), 'myMethod').mockImplementation(() => {//do stuff})
    

    【讨论】:

      猜你喜欢
      • 2021-04-03
      • 2018-08-31
      • 2020-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-15
      • 1970-01-01
      相关资源
      最近更新 更多