【发布时间】: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 <Component /> to have a 'component2' class, but it has 'component'。请注意缺少像您的消息那样的文字包装:<Wrapper(Component) />。 -
使用 mount 而不是 shallow 会产生
Invariant Violation: _registerComponent(...): Target container is not a DOM element.包装器包是react-onclickoutside,因此出现上述错误是有意义的,因为包没有安装任何 DOM 对象。在 DOM 中看起来像这样:<Wrapper(Component)> <Component /> </Wrapper(Component)> -
你知道浅层只会渲染一层 React 组件吗?这就是浅层和安装的区别。但听起来你有部分项目没有解释。也许将示例发布到 github/gist?
标签: testing reactjs mocha.js higher-order-functions enzyme