Test onClick with Jest Mock Function

1.1k Views Asked by At

I built a react app where I'm trying to get myself more confortable with testing, yet I'm quite stuck trying to test a button from my component. The documentation is very vague and I have not found any solution to my case.

The onClick method is simply calls a handleClick method like so at Body.js:

  const handleClick = () => {
      console.log('handling click')
  }
  

  return (
    <div className="container">
      I'm the body
      {posts &&
        posts.map((post, i) => {
          return (
            <div key={i}>
              <h1>{post.title}</h1>
              <p>{post.body}</p>
            </div>
          );
        })}
      <Button onClick={handleClick}>Get the posts</Button> // this button
    </div>
  );
};

I'm using mock function in my test like so:

  it('button triggers handleClick', () => {
    const fn = jest.fn();
    let tree = create(<Body onClick={fn} />);
    // console.log(tree.debug());
    // simulate btn click
    const button = tree.root.findByType('button');
    button.props.onClick();
    // verify callback
    console.log(fn.mock);
    expect(fn.mock.calls.length).toBe(1);
  });

But I cannot assert that the click was made.

expect(received).toBe(expected) // Object.is equality

    Expected: 1
    Received: 0

The handleClick method is working since I'm getting the desired output with console.log when I run the test.

  console.log
    handling click // it works!

      at Object.onClick (src/components/Body.js:9:15)

  console.log
    { calls: [], instances: [], invocationCallOrder: [], results: [] } // fn.mocks log

I'd appreciate any help.

Fernando,

0

There are 0 best solutions below