浅渲染不会渲染包装在Consumer(jest / Enzyme)中的组件

时间:2019-08-07 18:51:23

标签: javascript reactjs jestjs enzyme

我有这样一个组成部分:

import React from 'react';
import classNames from 'classnames/bind';

import { connect } from 'react-redux';

import Topic from './components/Topics';
import AutoItem from './AutoItem';
import DataContext from "./dataContext";

const cx = classNames.bind(Styles);

export class TestComponent extends React.Component {


  render() {


    return (
      <div>
              <DataContext.Consumer>
                {value => (
                  <AutoItem
                    data={value}
                  />
                )}
              </DataContext.Consumer>


            <DataContext.Consumer>
              {value => (
                <Topic data={value} />
              )}
            </DataContext.Consumer>

      </div>
    );
  }
}

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

const mapDispatchToProps = dispatch => ({
  ...
});

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

我想用玩笑/酶来测试它。我编写了这样的测试,以检查TestComponent内部渲染的Topic和AutoItem组件:

describe('<TestComponent  /> Component render', () => {

  let wrapper;

  beforeEach(() => {
    wrapper = shallow(<TestComponent {...props} />);
  });

  describe('<TestComponent  /> rendering', () => {

    test('should render child components in <TestComponent  /> component', () => {
      console.log(wrapper.debug())
      expect(wrapper.find(AutoItem).length).toEqual(1);
      expect(wrapper.find(Topic).length).toEqual(1);
    });

  });
});

但是测试失败,这就是控制台中的内容:

expect(received).toEqual(expected) // deep equality

    Expected: 1
    Received: 0

这是console.log(wrapper.debug())的输出:

<div className="">

            <ContextConsumer>
              [function]
            </ContextConsumer>
          </div>

          <ContextConsumer>
            [function]
          </ContextConsumer>


    </div>

我不明白为什么包装在Consumer中的组件不渲染并在控制台输出中显示为[function]。有人可以帮我吗?

"jest": "^24.8.0",
"babel-core": "^7.0.0-bridge.0",
"babel-jest": "^23.4.2",

基于答案,我这样写:

import DataContext from './dataContext';


test('should render child components in <TestComponent  /> component', () => {
      const wrapper = shallow(<TestComponent {...props} />)
        .find(DataConsumer.Consumer)
        .renderProp('children')();

          expect(wrapper.find(AutoItem).length).toEqual(1);
          expect(wrapper.find(Topic).length).toEqual(1);
    });

这就是我的浓奶油中的东西:

Expected: 1
Received: 0

这是调试包装程序时在控制台中看到的内容:

1 个答案:

答案 0 :(得分:1)

在酶中,您应该显式渲染renderPropenzyme