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

Oli*_*ins 5 reactjs enzyme react-redux

如果我使用模拟商店渲染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());

  }
Run Code Online (Sandbox Code Playgroud)

Test组件如下所示:

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

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

 <div className="here" />
Run Code Online (Sandbox Code Playgroud)

但是,如果我的组件是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)
Run Code Online (Sandbox Code Playgroud)

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

<BarSeriesListTest items={{...}} barData={{...}} dispatch={[Function]} />
Run Code Online (Sandbox Code Playgroud)

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

Mar*_*son 2

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

您应该使用酶的潜水功能,它将渲染子组件并将其作为包装器返回。

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

如果您有多个需要深入了解的组件,您可以多次使用它。它比使用mount也更好,因为我们仍在隔离测试。