0

我正在尝试模拟对反应组件中的 dom 元素的单击,并断言基于此调用了间谍。这是测试的相关部分(使用 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);
}

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

4

1 回答 1

1

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

尝试改变

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

TestUtils.Simulate.click(TestUtils.scryRenderedDOMComponentsWithTag(component, 'li')[0]); 
于 2016-03-22T11:17:43.160 回答