【问题标题】:.simulate('click') only working when done twice on the same component, through ID and Class.simulate('click') 仅在同一组件上通过 ID 和 Class 执行两次时才有效
【发布时间】:2017-08-20 10:30:43
【问题描述】:

我已经解决了现有问题,但找不到与此类似的问题。

我有一个类似这样的按钮元素,它位于我正在测试的 <Contact/> 组件中:

<div>
...
<button id="Contact-button-submit" className="btn btn-primary btn-lg" onClick={this.handleSubmit}>Submit</button>
...
</div>

这是我的测试:

it('calls handleSubmit when Submit button is clicked', () => {
    let wrapper = shallow(<Contact {...mockProps} />);
    wrapper.instance().handleSubmit = jest.fn();
    let { handleSubmit } = wrapper.instance();
    expect(handleSubmit).toHaveBeenCalledTimes(0);
    wrapper.find('#Contact-button-submit').simulate('click'); // the only simulate click I want
    wrapper.find('.btn-primary').simulate('click'); // the simulate click I also had to add
    expect(handleSubmit).toHaveBeenCalledTimes(1);
});

有趣的是,当我只包含第一次模拟点击(ID 一次)时,测试在最后一次预期失败。永远不会调用 onClick 函数 (handleSubmit)。 但是当我添加第二个使用 className 时,它​​通过了。

似乎他们都需要在场。如果删除一个,它将失败。

这有什么已知的原因吗?我正在为此挠头。

【问题讨论】:

  • 你控制台wrapper.find('#Contact-button-submit').wrapper.find('.btn-primary').
  • 是的,我对每个都做了 console.log(wrapper.find().debug())。他们都输出了相同的输出

标签: reactjs unit-testing jestjs


【解决方案1】:

我的解决方案是使用jest.spyOn

it('calls handleSubmit when Submit button is clicked', () => {
    const handleSubmit = jest.spyOn(Contact.prototype, 'handleSubmit');
    let wrapper = shallow(<Contact {...mockProps} />);
    expect(handleSubmit).toHaveBeenCalledTimes(0);
    wrapper.find('#Contact-button-submit').prop('onClick')();
    expect(handleSubmit).toHaveBeenCalledTimes(1);
});

问题是我在浅渲染后对方法进行了存根,而实际上我之前需要这样做。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-19
    • 2020-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多