是否有另一种方法可以在使用Jest时模拟组件的mapDispatchToProps

时间:2017-08-09 18:10:07

标签: reactjs jestjs enzyme

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

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这样的错误,因为信息没有被模拟/定义,但它没有&#39 ;吨。只有当函数不存在时才会抛出错误。

1 个答案:

答案 0 :(得分: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,只是为了告诉您,如果商店设置中配置了中间件,该怎么做。

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

但是,测试方法是相同的,除了您将创建具有expectedActions之类的显式动作类型的const expectedActions = ['FETCH_CONTACTS'] 这里的FETCH_CONTACT是您的重击中分派的另一个动作,即getDataAction

相关问题