模拟点击没有酶的反应

时间:2018-06-28 14:40:49

标签: reactjs unit-testing 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,因此第一个Expect语句成功运行。但是,第二项测试失败,控制台输出:

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

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

    Expected: true
    Received: false

这似乎暗示该模拟无效。我在这里做什么错了?

1 个答案:

答案 0 :(得分:2)

此问题是由引用在测试顶部创建的现有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);

解决了我的问题。

相关问题