测试React组件的onClick事件并包含多个动作 [英] Testing React component onClick event with multiple actions in it

查看:677
本文介绍了测试React组件的onClick事件并包含多个动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

无法弄清楚如何测试其中包含多个动作的onClick功能.

Can't figure it out how to test onClick function with multiple actions in it.

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

我目前进行的测试是这样的.

And the test I currently have is like this.

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));
});

我得到的结果就是这个.

The result i get is this.

AssertionError: expected [Function] to equal [Function]

推荐答案

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

The thing is that every call of Function.prototype.bind returns you a new function. So these functions are not equal

function onClick() {
}

console.log(onClick.bind() === onClick.bind()) // prints false

如果要检查按钮是否收到点击处理程序,则可以触发模拟点击并检查操作结果.另外,您可以模拟onClick监视功能.

If you want to check that button receives your click handler, you can trigger simulated click and check the result of the action. Also, you can mock onClick to spy function.

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..如果要针对商店测试组件,为确保已分派适当的操作,可以按以下方式进行操作.

UPD. If you want to test your component against the store, to be sure that proper actions were dispatched, you can do it in the following way.

首先,创建您的模拟商店:

First, create you mock store:

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

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

Then pass this store down to your component. (I assume that your MyComponent is connected to store)

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文档,以了解有关间谍检查的更多信息.

See Sinon documentation to learn more about spy checks.

这篇关于测试React组件的onClick事件并包含多个动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆