单元测试反应容器组件

时间:2021-02-26 17:31:33

标签: javascript reactjs unit-testing jestjs sinon-chai

我正在尝试使用 chai/sinon 对 React 容器组件进行单元测试。组件是这样定义的:

import { connect } from 'react-redux';
import React, { Component } from 'react';

class TestComponent extends Component {
  componentDidMount() {
    const { loadData } = this.props;
    loadData();
  }

  render() {
    const { links, heading } = this.props;
    return (
      <p>
        <h1>{heading}</h1>
        <div>{links.map(link => link.label)}</div>
      </p>
    );
  }
}

const mapStateToProps = state => ({
  heading: state.heading,
  links: state.links
});

const mapDispatchToProps = dispatch => ({
  loadData: dispatch('LOAD_DATA')
});

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

我正在编写一个单元测试来断言容器组件具有属性 loadData, headinglinks。下面是单元测试:

import configureStore from 'redux-mock-store';
import { Provider } from 'react-redux';
import React from 'react';
import { shallow } from 'enzyme';
import TestContainer from './TestContainer';

const mockStore = configureStore({});

describe('TestContainer', () => {
  const initialState = {
    heading: 'A test component',
    links: []
  };
  const store = mockStore(initialState);
  it(
    'renders correctly',
    sinon.test(() => {
      const component = shallow(
        <Provider store={store}>
          <TestContainer />
        </Provider>
      );
      console.log(component.prop('heading')); // prints undefined

      expect(component.prop('heading')).to.equal('A test component'); // gives AssertionError: expected undefined to equal 'A test component'
    })
  );
});

以上单元测试失败,我将所有道具设为未定义。有人可以解释我做错了什么或应该如何断言容器组件道具吗?

谢谢。

0 个答案:

没有答案