【问题标题】:Simulate click - enzyme模拟点击酶
【发布时间】:2018-01-18 19:17:50
【问题描述】:

我在使用 Enzyme 工具测试 React 应用时遇到问题。

在我的组件中,我有登录表单,我想测试点击按钮后 p 标签是否会被文本填充。

实际上点击提交后,有向api发送请求(现在不存在),返回了关于无法访问端点的错误。

尝试以多种方式对其进行测试,但发现了一件有趣的事情。使用:

it('returns error if endpoint not reachable', () => {
    const wrapper = mount(<LoginForm dispatch={dispatch} store={store} />);
    wrapper.find('button').simulate('click');
    console.log(wrapper.debug());
  });

在控制台中返回 HTML 代码。但是还有p标签也没有填写。所以我的问题是如何在这里使用模拟功能?

第一次我以为是超时造成的。但是使用 setTimeout 会得到相同的结果。

感谢您的帮助!

【问题讨论】:

    标签: reactjs react-redux enzyme


    【解决方案1】:

    Enzyme 提供了提交点击事件的能力。如果它不起作用,我很好奇您是否选择了正确的元素。文档中的示例...

    https://github.com/airbnb/enzyme/blob/master/docs/api/ShallowWrapper/simulate.md#example

    class Foo extends React.Component {
      constructor(props) {
        super(props);
        this.state = { count: 0 };
      }
      render() {
        const { count } = this.state;
        return (
          <div>
            <div className={`clicks-${count}`}>
              {count} clicks
            </div>
            <a href="url" onClick={() => { this.setState({ count: count + 1 }); }}>
              Increment
            </a>
          </div>
        );
      }
    }
    
    const wrapper = shallow(<Foo />);
    
    expect(wrapper.find('.clicks-0').length).to.equal(1);
    wrapper.find('a').simulate('click');
    expect(wrapper.find('.clicks-1').length).to.equal(1);
    

    因此,在您的特定情况下,您提到在单击提交按钮后会进行 API 调用。您需要使用像 Sinon 这样的东西来隔离和模拟这种行为。

    http://sinonjs.org/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-02-06
      • 2018-03-30
      • 2018-02-24
      • 1970-01-01
      • 1970-01-01
      • 2018-12-07
      • 2018-11-05
      相关资源
      最近更新 更多