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

1 testing mocha.js higher-order-functions reactjs enzyme

我在 React 组件中使用HOC,如下所示:

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

使用 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');
  });
});
Run Code Online (Sandbox Code Playgroud)

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

我收到的错误是:

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

     <div class="component">
     </div>
Run Code Online (Sandbox Code Playgroud)

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

Alb*_*ivé 5

您可以使用酶.dive()

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

expect(component.props().className).toEqual('component')
Run Code Online (Sandbox Code Playgroud)