使用 Jest Mock 函数测试 onClick

问题描述

我构建了一个 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

感谢您的帮助。

费尔南多,

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...