使用 Jest Mock 函数测试 onClick

时间:2021-02-10 01:46:59

标签: reactjs jestjs jest-fetch-mock

我构建了一个 React 应用程序,我试图让自己更适应测试,但我在尝试从我的组件测试 button 时遇到了困难。文档非常模糊,我还没有找到任何解决方案。

onClick 方法只是调用一个 handleClick 方法,就像在 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>
  );
};

我在测试中使用模拟函数,如下所示:

  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);
  });

但我不能断言点击是发生的。

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

    Expected: 1
    Received: 0

handleClick 方法正在运行,因为我在运行测试时使用 console.log 获得了所需的输出。

  console.log
    handling click // it works!

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

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

感谢您的帮助。

费尔南多,

0 个答案:

没有答案