问题
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