酶:浅层渲染内部 react-redux 组件

Enzyme: shallow render inner react-redux components

我有一个简单的反应组件,它使用来自 antd 的卡片:

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

export class TBD extends Component {

  constructor() {
    super();
  }

  render() {
    return (
      <Card title={this.props.pathname}>
        TODO
      </Card>
    );
  }
}

export let select = (state) => {
  return state.route;
};

export default connect(select)(TBD);

现在我写了一些简单的测试并想检查我的 TBD 组件是否使用 Card

import React from 'react';
import {mount, shallow}  from 'enzyme';
import {Provider, connect}  from 'react-redux';
import {createMockStore}  from 'redux-test-utils';
import {expect} from 'chai';
import chai from 'chai';
import chaiEnzyme from 'chai-enzyme';
chai.use(chaiEnzyme());
import { Card } from 'antd';
import TBDConnected,  {TBD, select} from '../src/js/components/TBD';

describe('Fully Connected:', function () {
    it('show selected item text', function () {

      const expectedState = {route: {pathname: 'Menu1'}};
      const store = createMockStore(expectedState);
      const ConnectedComponent = connect(select)(TBDConnected);
      const component = shallow(<ConnectedComponent store={store} />).shallow().shallow();
      console.log(component.debug());
      expect(component.equals(<Card/>)).is.equal(true);
    });
  });

它失败了,因为 3 浅 return 我

<Component title="Menu1">
TODO
</Component>

但我期待

<Card title="Menu1">
TODO
</Card>

再渲染一次后,我从渲染 Card 中得到纯粹的 html 我不明白为什么它将它渲染到 Component 而不是 Card 以及我如何获得我想要的结果。

更新

示例简化了我的问题。下一次测试失败:

describe('TBD', function () {
  it('Renders a Card', function () {
    const component = shallow(<TBD />);
    console.log(component.debug());
    expect(component.equals(<Card/>)).is.equal(true);
  });
});

控制台中的调试输出:

<Component title={[undefined]}>
TODO
</Component>

但我预计:

<Card title={[undefined]}>
TODO
</Card>

您不需要测试整个连接的组件。 我会先测试演示纯组件(作为单元测试),然后您可以单独测试连接器

I.E.

import React from 'react';
import {shallow}  from 'enzyme';
import {expect} from 'chai';
import chai from 'chai';
import chaiEnzyme from 'chai-enzyme';
chai.use(chaiEnzyme());
import { Card } from 'antd';
import {TBD} from '../src/js/components/TBD';

describe('TBD', function () {
  it('Renders a Card', function () {
    const component = shallow(<TBD />);
    expect(component.equals(<Card/>)).is.equal(true);
  });
  it('sets the right title', function () {
    const component = shallow(<TBD pathname="example" />);
    expect(component.prop('title')).is.equal("example");
  });
});

如您所见,您的纯组件必须作为纯函数进行测试。你传递了一些道具并期待一些渲染。

然后当您测试连接器时,您可以断言它正确映射了 stateToProps 和 dispatchToProps...

Ant Delvelope 组件中的问题。此组件的一部分编写为简单的匿名函数,没有扩展 React.Component 等。结果 Enzyme 将其呈现为 <Component />,在浏览器中它看起来像 <StatelessComponent />.