首页 > 解决方案 > 模拟点击 React with Enzyme 不做任何事情

问题描述

我有一个 React 组件类,我正在尝试测试点击行为,但对于我的生活,我无法让模拟实际运行。这是组件类:

class Navbar extends Component {
  constructor(props) {
    super(props);

    this.toggle = this.toggle.bind(this);
    this.state = {
      isOpen: false
    };
  }

  toggle() {
    this.setState({
      isOpen: !this.state.isOpen
    });
  }

  render() {
    return (
      <NavbarWrapper expand={this.props.expand}>
        <NavbarBrand>{logo}</NavbarBrand>
        <NavbarToggler onClick={this.toggle} collapsed={!this.state.isOpen}>
          <NavbarIconBar className="top-bar" />
          <NavbarIconBar className="middle-bar" />
          <NavbarIconBar className="bottom-bar" />
        </NavbarToggler>
        <NavbarCollapsibleContent isOpen={this.state.isOpen} navbar>
          {this.props.children}
        </NavbarCollapsibleContent>
      </NavbarWrapper>
    );
  }
}

这是测试:

const wrapper = shallow(<Navbar {...props} />);
const toggler = wrapper.find(NavbarToggler);
const content = wrapper.find(NavbarCollapsibleContent);

// initial state
expect(content.props().isOpen).toBe(false);

// click to expand (i.e. NOT collapse)
toggler.simulate("click");
expect(content.props().isOpen).toBe(true);

// click to collapse
toggler.simulate("click");
expect(content.props().isOpen).toBe(false);

由于组件isOpen属性的初始状态是false,所以第一个期望语句运行成功。但是,第二个测试失败,控制台输出:

  ● Navbar › should toggle 'NavbarCollapsibleContent's 'isOpen' state when clicking on 'NavbarToggler'

    expect(received).toBe(expected) // Object.is equality

    Expected: true
    Received: false

这似乎暗示模拟不起作用。我在这里做错了什么?

标签: reactjsunit-testingenzyme

解决方案


该问题是由于引用了const content在测试顶部创建的现有内容而引起的,该内容在更新后变得陈旧。将测试套件更改为:

const wrapper = shallowTestComponent();
const toggler = wrapper.find(NavbarToggler);

// initial state
expect(wrapper.find(NavbarCollapsibleContent).props().isOpen).toBe(false);

// click to expand (i.e. NOT collapse)
toggler.simulate("click");
expect(wrapper.find(NavbarCollapsibleContent).props().isOpen).toBe(true);

// click to collapse
toggler.simulate("click");
expect(wrapper.find(NavbarCollapsibleContent).props().isOpen).toBe(false);

解决了我的问题。


推荐阅读