【问题标题】:is there another way to mock component's mapDispatchToProps when using Jest使用 Jest 时是否有另一种方法来模拟组件的 mapDispatchToProps
【发布时间】:2018-01-17 18:22:41
【问题描述】:

我目前有一个这样的组件:

import React, { Component } from 'react';
import { connect } from 'react-redux';
import { getDataAction } from ' './my-component';

export class MyComponent extends { Component } {
   componentWillMount() {
      this.props.getData();
   }
   render(){

      <div>
      this.props.title
     </div>

   }
}

const mapStateToProps = (state) => ({
   title: state.title
});

const mapDispatchToProps = (dispatch) ({
   getData() {
      dispatch(getDataAction());
   }
});

export default connect(mapStateToProps, mapDispatchToProps)(MyComponent)

我正在尝试使用 jest 和酶对其进行浅渲染测试。

测试:

import React from 'react';
import { shallow } from 'enzyme';
import { MyComponent } from './index';

it('renders without crashing', () => {
  shallow(<MyComponent getData={jest.fn()} />);
});

我的问题是,这是传统的模拟方式吗? Jest 官方文档没有特别提到模拟道具,而这篇文章Using Jest to mock a React component with props 是关于完全安装的测试。 还有另一种模拟 dispatchToProps 的方法吗?在这个例子中只有一个,但是如果我在 dispatchToProps 中有很多函数呢?

附带问题:在我的真实文件中,我有一个像 this.props.information.value 这样的值的引用,我希望会抛出像 cannot get value of undefined 这样的错误,因为信息没有被模拟/定义,但它没有。只有当函数不存在时才会抛出错误。

【问题讨论】:

    标签: reactjs jestjs enzyme


    【解决方案1】:

    您可以导出 mapDispatchToProps 并通过在测试中导入它来为其编写测试。

    MyComponent.js

    的末尾添加 export { mapDispatchToProps };

    MyComponent.js

    旁边创建MyComponent.tests.js文件
    import configureMockStore from 'redux-mock-store';
    import thunkMiddleware from 'redux-thunk';
    import { mapDispatchToProps } from './MyComponent';
    
    const configMockStore = configureMockStore([thunkMiddleware]);
    const storeMockData = {};
    const mockStore = configMockStore(storeMockData);
    
    describe('mapDispatchToProps', () => {
      it('should map getDataAction action to getData prop', () => {
         // arrange
         const expectedActions = [getDataAction.type];
         const dispatchMappedProps = mapDispatchToProps(mockStore.dispatch);
         // act
         dispatchMappedProps.getData();
         // assert
         expect(mockStore.getActions().map(action => action.type)).toEqual(expectedActions);
      }
    });
    

    这里我使用了 thunk,只是为了让您知道如果您的商店设置中配置了中间件,该怎么做。

    这里getDataAction 也可以是一个函数,而不是像{ type: 'FETCH_DATA' } 这样的简单操作,如果您使用的是像thunk 这样的中间件。

    但是,测试方法是相同的,只是您将创建 expectedActions 并使用像 const expectedActions = ['FETCH_CONTACTS'] 这样的显式操作类型

    这里FETCH_CONTACT 是在您的thunk 中调度的另一个动作,即getDataAction

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-04-07
      • 2019-05-30
      • 2017-12-15
      • 1970-01-01
      • 2021-01-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多