【问题标题】:Using Mocha to test higher order components in React使用 Mocha 测试 React 中的高阶组件
【发布时间】:2016-06-29 17:48:41
【问题描述】:

我在 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 测试组件时,我试图寻找一个应该包含在 Component 中的类名。像这样:

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

问题在于 Mocha 不知道在包装器中查找 Component 并尝试在 HOC 中找到它。当然不会。

我收到的错误是:

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

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

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

【问题讨论】:

  • 我猜问题是您使用的是shallow 而不是mount
  • 其实,我的测试通过了。
  • 那个包装包是什么?我将 css 类更改为“component2”以强制测试失败,然后它告诉我AssertionError: expected &lt;Component /&gt; to have a 'component2' class, but it has 'component'。请注意缺少像您的消息那样的文字包装:&lt;Wrapper(Component) /&gt;
  • 使用 mount 而不是 shallow 会产生 Invariant Violation: _registerComponent(...): Target container is not a DOM element. 包装器包是 react-onclickoutside,因此出现上述错误是有意义的,因为包没有安装任何 DOM 对象。在 DOM 中看起来像这样:&lt;Wrapper(Component)&gt; &lt;Component /&gt; &lt;/Wrapper(Component)&gt;
  • 你知道浅层只会渲染一层 React 组件吗?这就是浅层和安装的区别。但听起来你有部分项目没有解释。也许将示例发布到 github/gist?

标签: testing reactjs mocha.js higher-order-functions enzyme


【解决方案1】:

你可以用酵素.dive()

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

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

【讨论】:

    【解决方案2】:

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

    所以,请使用mount

    我将此添加到 github 项目中,以便您查看。使用我的redux-form-test 项目并确保使用stackoverflow-question-38106763 分支。请参阅tests/unit/index.js 文件。

    请务必阅读测试文件的源代码。其中一项测试故意未能重现您的问题。

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

    console.log(component.debug())
    

    在您的 expect 之前,它会显示

    <Component />
    

    那是因为shallow 只深了一层。并且酶没有使用渲染的 HTML 进行断言,它使用的是 React 元素,它没有 component 类,如您所见。

    【讨论】:

    • 谢谢,泰勒!我没有测试您的答案,但我会将其标记为已接受,因为这似乎是问题所在。感谢您花时间回答这个问题。一定要爱腓尼基人帮助(前)腓尼基人!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    • 2017-04-19
    • 2017-02-12
    • 2018-11-18
    • 1970-01-01
    • 2017-09-26
    相关资源
    最近更新 更多