【问题标题】:React Test Utils - Spy not called when a simulated click is performed -React Test Utils - 执行模拟点击时未调用 Spy -
【发布时间】:2016-07-09 05:12:03
【问题描述】:

我正在尝试模拟对 react 组件中的 dom 元素的单击,并断言基于此调用了 spy。这是测试的相关部分(使用 karma、mocha、chai、sinon,但我很确定这与这里无关):

const selectSpy = sinon.spy();
const component = TestUtils.renderIntoDocument(<SomeComponent onSelect={selectSpy} />);
TestUtils.Simulate.click(TestUtils.scryRenderedDOMComponentsWithTag(component, 'li'));
expect(selectSpy.called).to.be.ok;

这是反应组件:

render() {
    let { title , data, onSelect }  = this.props;
    console.log(this.props.onSelect); // This correctly logs out the spy
    return (
      <div>
        <ul>{data.map((row, i) => {
          return <li onClick={this.handle.bind(this,row)} key={i}>{row.title}</li>; })}
        </ul>
      </div>
    )
}

handle(row) {
    this.props.onSelect(row);
}

测试运行,但结果是测试失败,并显示消息“预期为假为真”。我看不出代码有什么问题——没有错误,我的间谍正确传递。 还有什么我需要做的吗?

【问题讨论】:

    标签: unit-testing reactjs reactjs-testutils


    【解决方案1】:

    TestUtils.Simulate.click 需要一个 DOM 元素,但 scryRenderedDOMComponentsWithTag 返回一个 DOM 元素数组。

    尝试改变

    TestUtils.Simulate.click(TestUtils.scryRenderedDOMComponentsWithTag(component, 'li'));
    

    TestUtils.Simulate.click(TestUtils.scryRenderedDOMComponentsWithTag(component, 'li')[0]); 
    

    【讨论】:

    • 就是这样。非常感谢
    猜你喜欢
    • 2019-06-22
    • 2019-03-04
    • 2018-09-01
    • 2017-12-27
    • 2020-12-30
    • 2019-08-08
    • 2019-05-13
    • 2019-03-07
    • 1970-01-01
    相关资源
    最近更新 更多