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>
`;