酶浅层渲染只是redux组件中的一个节点

时间:2017-10-22 15:01:05

标签: reactjs react-redux enzyme

如果我使用模拟商店渲染redux组件,则酶浅渲染会以意想不到的方式运行。

我有一个简单的测试,如下所示:

  import React from 'react';
  import { shallow } from 'enzyme';
  import { createMockStore } from 'redux-test-utils';

  import Test from './Test'

  it('should render ', () => {
    const testState = {
      app: {
        bar: ['a', 'b', 'c']
      }
    };

    const store = createMockStore(testState)
    const context = {
      store,
    };
    const shallowComponent = shallow(<Test items={[]}/>, {context});

    console.log(shallowComponent.debug());

  }

测试组件如下所示:

class Test extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return(
      <div className="here"/>
    )
  }
}
export default Test;

正如预期的那样打印出来:

 <div className="here" />

但是,如果我的组件是redux组件:

class Test extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return(
      <div className="here"/>
    )
  }
}
const mapStateToProps = state => {
  return {
    barData: state.app.bar
  }
}

export default connect(
  mapStateToProps
)(Test)

然后我在控制台得到的是:

<BarSeriesListTest items={{...}} barData={{...}} dispatch={[Function]} />

为什么会出现这种差异?如何在组件的redux版本中测试我的组件是否嵌入了<div className="here"/>

3 个答案:

答案 0 :(得分:2)

您正在引用connect正在返回的HOC,而不是您要测试的组件。

你应该使用酶的dive函数来渲染子组件并将其作为包装器返回。

const shallowComponent = shallow(<Test items={[]}/>, {context}).dive();

如果您有多个需要潜水的组件,您可以多次使用它。它比使用mount更好,因为我们仍在单独测试。

答案 1 :(得分:1)

您应该导出未连接的组件并单独测试(注意第一个export):

export class Test extends React.Component {

}
...
export default connect(
  mapStateToProps
)(Test)

在测试中,你应该像这样测试未连接组件的渲染(注意{ Test }周围的花括号):

import React from 'react';
import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';
import { Test } from './Test';

describe('...', () => {
  it('...', () => {
    const wrapper = shallow(<Test />)
    expect(toJson(wrapper)).toMatchSnapshot();
  })
})

希望这有帮助。

模式专门针对您所描述的情况,组件应为:

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

export class Test extends React.Component {
  constructor(props) {
    super(props);
  }
  render() {
    return(
      <div className="here"/>
    )
  }
}
const mapStateToProps = state => {
  return {
    barData: state.app.bar
  }
}

export default connect(
  mapStateToProps
)(Test)

测试规范应该是:

import React from 'react';
import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';
import { Test } from 'Test';

describe('Test component', () => {
  it('renders', () => {
    const wrapper = shallow(<Test />);
    expect(toJson(wrapper)).toMatchSnapshot();
  });
});

生成以下快照:

exports[`Test component renders 1`] = `
<div
  className="here"
/>
`;

答案 2 :(得分:1)

默认情况下,您正在导出连接的组件。您可以做的是导入未连接到redux的组件。

import { Test } from './Test';

然后你的测试应该有效。

相关问题