Testing React component onClick event with multiple actions in it

巧了我就是萌 提交于 2020-02-06 05:16:15

问题


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]

回答1:


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

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. 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
   }
}

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

See Sinon documentation to learn more about spy checks.



来源:https://stackoverflow.com/questions/35478076/testing-react-component-onclick-event-with-multiple-actions-in-it

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!