我试图模拟一个名为actionClicked的props ,但我的测试失败了,我有一个简单的组件,如下所示

const ButtonAction: React.FC = ({ actionClicked }) => {
    const handleClick = (action) => () => actionClicked(action)
  
    return (
          <div
            data-testid="some-action"
            onClick={handleClick('something')}
          >
              <Icon />
          </div>
    )
  }

这是我的测试,巴顿.规格tsx

import { render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'

import React from 'react'

import ButtonAction from './ButtonAction'

test('render ButtonAction', () => {
  const actionClicked = jest.fn()

  render(<ButtonAction actionClicked={actionClicked} />)

  userEvent.click(screen.getByTestId('some-action'))
  expect(actionClicked).toHaveBeenCalled() //failed here
})

我不知道为什么没有叫actionClicked.

Expected number of calls: >= 1
Received number of calls:    0

有什么 idea 吗?

推荐答案

发生这种行为是因为userEvent.click返回promise .

首先,您应该将测试设置为async,然后设置为await userEvent.click:

test("render ButtonAction", async () => {
  const actionClicked = jest.fn();

  render(<ButtonAction actionClicked={actionClicked} />);

  await userEvent.click(screen.getByTestId("some-action"));

  expect(actionClicked).toHaveBeenCalledTimes(1);
});

Javascript相关问答推荐

react 页面更改类别时如何返回第0页

React:如何将表格收件箱正确渲染为表格主体内的组件?

自定义帖子类型帖子未显示在网站上

获取加载失败:获取[.]添加时try 将文档添加到Firerestore,Nuxt 3

RxJS setTimeout操作符等效

每次子路由重定向都会调用父加载器函数

我可以使用CSS有效地实现最大宽度=100%和最大高度=100%,而无需父母有明确的/固定的宽度和高度,替代方法吗?

Chrome是否忽略WebAuthentication userVerification设置?""

Mongoose post hook在使用await保存时不返回Postman响应

虚拟滚动实现使向下滚动可滚动到末尾

如何将react—flanet map添加到remixjs应用程序

在Reaction中的handleSubmit按钮内,useSelector值仍然为空

根据一个条件,如何从处理过的数组中移除一项并将其移动到另一个数组?

使用插件构建包含chart.js提供程序的Angular 库?

try 将Redux工具包与MUI ToggleButtonGroup组件一起使用时出错

如何为仅有数据可用的点显示X轴标签?

如何使用Astro优化大图像?

如何组合Multer上传?

在Java脚本中录制视频后看不到曲目

是否设置以JavaScript为背景的画布元素?