1

I'm trying to simulate a click on a button but the test always fails and I have no idea why. It seems that enzyme can't select the DOM element to trigger a click on it, because the calls are always 0. I am using enzyme 3.7.0 and jest 23.6.0

Button.tsx

import * as React from 'react';
import './button.scss';

export interface IButton {
  value: string;
  onClick: () => void;
}

class Button extends React.Component<IButton, {}> {
  render() {
    return (
      <div className="Button">
        <button id="btn" onClick={this.props.onClick} className="Button__btn" type="button">
          {this.props.value}
        </button>
      </div>
    );
  }
}

export default Button;

Button.test.tsx

import * as React from 'react';
import { shallow } from 'enzyme';
import Button  from './Button';

test.only('Button test', () => {
  const myMock = jest.fn();

  const mockedButton = shallow(<Button value="testvalue" onClick={() => myMock} />);
  console.log(mockedButton.debug());

  // Interaction demo
  expect(mockedButton.text()).toEqual('testvalue');

  mockedButton.find('button').simulate('click');
  mockedButton.find('.Button__btn').simulate('click');
  mockedButton.find('button.Button__btn').simulate('click');
  expect(myMock.mock.calls.length).toBe(0); // !! Should be 3 ?

  // Snapshot demo
  expect(mockedButton).toMatchSnapshot();
});

However, the snapshot generated could allow me to select the right element (button)

exports[`Button test 1`] = `
<div
  className="Button"
>
  <button
    className="Button__btn"
    onClick={[Function]}
  >
    testvalue
  </button>
</div>
`;

1 Answer 1

2

The reason is this part:

onClick={() => myMock}

Here you describe click handler that returns your mock instead of calling it. It should be onClick={() => myMock()} or better just onClick={myMock}

instead. There React will call your myMock on .simulate('click')

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

Comments

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.