在 React 中使用 Mocha 测试高阶组件

Using Mocha to test higher order components in React

我在 React 组件中使用 HOC,看起来像:

import React from 'react';
import Wrapper from 'wrapper';
class Component extends React.Component {
  render () {
    return (
      <div className='component' />
    )
  };
}
export default Wrapper(Component)

在使用 Mocha 测试组件时,我试图寻找一个 class 应该包含在组件中的名称。像这样:

describe('Component', function () {
  it('can be mounted with the required class', function () {
    const component = shallow(
      <Component />
    );
    expect(component).to.have.className('component');
  });
});

问题是 Mocha 不知道在组件的包装器中查找并尝试在 HOC 中找到它。当然不会。

我收到的错误是:

AssertionError: expected <Wrapper(Component) /> to have a 'component' class, but it has undefined
     HTML:

     <div class="component">
     </div>

如何告诉 Mocha 在 HOC 中查找 class 名称的正确位置而不是 HOC 本身?

问题是使用 Enzyme 的 shallow 而不是测试 HOC 时需要的 mount

所以,使用mount.

我将其添加到 github 项目中以便您查看。使用我的redux-form-test项目,一定要使用Whosebug-question-38106763分支。请参阅 tests/unit/index.js 文件。

Be sure to read the source code of the test file. One of tests fails intentionally to reproduce your issue.

在这种情况下棘手的是 HOC 的渲染方法准确地复制了它包装的组件。请参阅 render 方法 in the source of the react-onclickoutside component you mention。这就是为什么您看到的 AssertionError 令人困惑:它向您显示 HTML 看起来它满足断言。但是,如果您 运行

console.log(component.debug())

在您的 expect 之前,它会显示

<Component />

那是因为 shallow 只深入一层。并且酶没有使用呈现的 HTML 作为断言,它使用的是 React 元素,它上面没有 component class,如您所见。

你可以使用酵素.dive()

const component = shallow(<Component />).dive();

expect(component.props().className).toEqual('component')