1

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 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Doing this throws another error: TypeError: Attempted to assign to readonly property. But even so, this will only check if click happens, would be really great to check if certains actions are actually called.
Well, then you can instantiate your component with a fake store with a spy on dispatch. Updated the answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.