【问题标题】:Testing React component onClick event with multiple actions in it测试包含多个操作的 React 组件 onClick 事件
【发布时间】:2016-05-30 10:03:15
【问题描述】:

不知道如何测试包含多个操作的 onClick 函数。

onButtonClick = function(action){
  this.props.otherAction();
  action();
}
...
<Button bsStyle="success" bsSize="small" onClick={onButtonClick.bind(this,someAction}>
  Something
</Button>

而我目前的测试是这样的。

const onButtonClick = function (action) {
  actions.otherAction();
  action();
};

it('Should include a button with multiple actions on onClick event.', function () {
    const button = shallowTestUtils.findAllWithType(_component, Button);
    expect(button[0].props.onClick).to.equal(onButtonClick.bind(this, actions.someAction));
});

我得到的结果是这样的。

AssertionError: expected [Function] to equal [Function]

【问题讨论】:

    标签: reactjs redux react-bootstrap reactjs-testutils


    【解决方案1】:

    问题是每次调用Function.prototype.bind 都会返回一个新函数。所以这些函数不相等

    function onClick() {
    }
    
    console.log(onClick.bind() === onClick.bind()) // prints false
    

    如果您想检查该按钮是否接收到您的点击处理程序,您可以触发模拟点击并检查操作的结果。此外,您可以模拟onClick 来监视功能。

    it('should trigger handler on button click', function () {
      // mock actual action
      _component.onClick = sinon.spy();
    
      // find button and trigger click on it
      const button = shallowTestUtils.findAllWithType(_component, Button)[0];
      ReactTestUtils.Simulate.click(findDOMNode(button));
      expect(_component.onClick.called).to.be.ok();
    });
    

    UPD。如果您想针对商店测试您的组件,以确保调度了正确的操作,您可以通过以下方式进行。

    首先,创建模拟商店:

    const mockStore = {
       dispatch: sinon.spy(),
       getState() {
         // here you can return some mock state
       }
    }
    

    然后将此存储传递给您的组件。 (我假设您的MyComponent 已连接到商店)

    const component = TestUtils.createRenderer().render(<MyComponent store={mockStore}>)
    
    const button = shallowTestUtils.findAllWithType(component, Button)[0];
    ReactTestUtils.Simulate.click(findDOMNode(button));
    // here you can check that dispatch was called with all expected actions
    expect(mockStore.dispatch.calledWith({type: 'ACTION_TYPE'})).to.be.ok();
    

    请参阅Sinon documentation 了解有关间谍检查的更多信息。

    【讨论】:

    • 这样做会引发另一个错误:TypeError: Attempted to assign to readonly property。但即便如此,这只会检查是否发生了点击,检查是否确实调用了某些操作真的很棒。
    • 好吧,那么您可以使用带有dispatch 的间谍的虚假商店来实例化您的组件。更新了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-19
    • 1970-01-01
    • 2020-07-19
    • 2018-03-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多