我在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时,我试图查找应该包含在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本身?
答案 0 :(得分:4)
您可以使用酶.dive()
const component = shallow(<Component />).dive();
expect(component.props().className).toEqual('component')
答案 1 :(得分:0)
问题是使用酶shallow
代替mount
,这在测试HOC时是必需的。
因此,请使用mount
。
我将此添加到github项目中,以便您可以看到。使用我的redux-form-test项目并确保使用stackoverflow-question-38106763
分支。请参阅tests/unit/index.js
文件。
请务必阅读测试文件的源代码。其中一项测试无意故意重现您的问题。
在这种情况下,棘手的是HOC的渲染方法完全复制了它包装的组件。请参阅render
方法in the source of the react-onclickoutside component you mention。这就是为什么你看到的AssertionError
令人困惑的原因:它向你显示看起来像是满足断言的HTML。但是,如果你运行
console.log(component.debug())
在expect
之前,它会显示
<Component />
那是因为shallow
只有一个深度。并且酶没有使用呈现的HTML作为断言,它正在使用React元素,它上面没有component
类,如您所见。