menu

Testing Library

Simple and complete DOM testing utilities that encourage good testing practices.

Channels
Chat
view-forward
# All channels
view-forward
# General
view-forward
# General Help
view-forward
# Angular Help
view-forward
# Cypress Help
view-forward
# DOM Help
view-forward
# React Help
view-forward
# TestCafe Help
view-forward
# Vue Help
view-forward
Team

fireEvent.click on functional components

February 21, 2020 at 7:09pm

fireEvent.click on functional components

February 21, 2020 at 7:09pm
Hi ,
Can anyone please help me with the below:
Code I am testing:
const Myapp = (props) => {
const handleClick = (e) => {
// does some stuff
};
return(
<div>
<button
type="button"
className="className"
onClick={ e => handleClick(e) }
>
<span className="btn-label">Save</span>
</button>
</div>
)};
My Test:
test("check handleClick is called on onClick", () => {
const { container, getByText } = render(<MyApp { ...props } />);
const handleClick = jest.fn();
expect(container).toMatchSnapshot();
fireEvent.click(getByText(/Save/i));
expect(handleClick).toHaveBeenCalled();
});

February 21, 2020 at 7:13pm
This is the error message i am getting `Error: expect(jest.fn()).toHaveBeenCalled()
Expected mock function to have been called.`
  • reply
  • like
The handleClick mock is not connected to the component at all. Clicking the button calls the handleClick within that component.
  • reply
  • like
Thanks . So, you are suggesting something like below:
const Myapp = (props) => {
const handleClick = (e) => {
// does some stuff
};
return(
<div>
<button
type="button"
className="className"
onClick={ e => handleClick(e) }
>
<span className="btn-label">Save</span>
</button>
</div>
)};
MyApp.propTypes = {
handleClick: propTypes.func
}
and then the test is
test("check handleClick is called on onClick", () => {
const { container, getByText } = render(<MyApp { ...props } handleClick = {handleClick} />);
const handleClick = jest.fn();
expect(container).toMatchSnapshot();
fireEvent.click(getByText(/Save/i));
expect(handleClick).toHaveBeenCalled();
});
?
  • reply
  • like
With some more modifications, that approach could work. However that is testing implementation details, which is generally not a quality test. You would be better off removing the mock and the snapshot, since that doesn't provide value either. Then have the component update the DOM in some way when handleClick is called within in the component. This DOM update would be what the end user would expect to see. Then back in the test, assert that the DOM was updated properly. That process will let you know the component is behaving as the user would expect it to.
  • reply
  • like
Agreed. It also depends on what the click handler is doing. If it changes the DOM, then assert that the DOM changed. If it is executing some side effect like a network request, the I would recommend using a module mock.
like-fill
1
  • reply
  • like