我已经创建了一个Reaction组件,当单击该组件时会执行动画,在动画结束后会运行回调.我想使用Jest和Reaction测试库测试此功能.这是我的组件:

export const Valuable = ({ onClick }) => {
  const [isClicked, setIsClicked] = useState(false);
  const handleClick = () => {
    setIsClicked(true);
  };
  const handleAnimationEnd = () => {
    setIsClicked(false);
    onClick();
  };

  return (
    <div
      className={isClicked ? 'animate-valuable ' : ''}
      onClick={handleClick}
      onAnimationEnd={handleAnimationEnd}
      data-testid="valuable-container"
    >
      ...
    </div>
  );
};

测试:

describe('Valuable', () => {
  const valuableProps = {
    onClick: jest.fn(),
  };
  beforeEach(() => {
    render(<Valuable {...valuableProps} />);
  });

  it('should execute on click callback', () => {
    expect(valuableProps.onClick).not.toHaveBeenCalled();
    const container = screen.getByTestId('valuable-container');
    expect(container).toBeInTheDocument();
    fireEvent.click(container);
    expect(valuableProps.onClick).toBeCalledTimes(1);
    fireEvent.click(container);
    fireEvent.click(container);
    expect(valuableProps.onClick).toBeCalledTimes(3);
  });
});

这是我收到的错误

  ● Valuable › should execute on click callback

    expect(jest.fn()).toHaveBeenCalledTimes(expected)

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

推荐答案

我的假设是您在jsdom环境中运行测试.每React Testing Library Setup docs人:

然而,大多数使用REACT测试库的人将其与Jest测试框架一起使用,并将testEnvironment设置为jest-Environment-jsdom(这是Jest 26及更早版本的默认配置).Jsdom是在Node中运行的DOM和浏览器API的纯JavaScript实现.

如果是这样的话,the animationend event is not supported in jsdom.

您可以通过明确的firing the animationend event%来解决此问题:

  it('should execute on click callback', () => {
    expect(valuableProps.onClick).not.toHaveBeenCalled();
    const container = screen.getByTestId('valuable-container');
    expect(container).toBeInTheDocument();
    fireEvent.click(container);
    expect(valuableProps.onClick).toBeCalledTimes(0);
    fireEvent.animationEnd(container);
    expect(valuableProps.onClick).toBeCalledTimes(1);
    fireEvent.click(container);
    fireEvent.animationEnd(container);
    fireEvent.click(container);
    fireEvent.animationEnd(container);
    expect(valuableProps.onClick).toBeCalledTimes(3);
  });

Javascript相关问答推荐

Snowflake - .toISOString()错误地舍入JS存储过程中的时间戳

想要检测字符串中的所有单词

Fastify错误:CORS策略已阻止从起源api-dev.example.com上的MLhttp请求

在分区内迭代分区

materialized - activeIndex返回-1

如何将连续的十六进制字符串拆分为以空间分隔的十六进制块,每个十六进制块包含32个二元组?

我不知道为什么setwritten包装promise 不能像我预期的那样工作

将旋转的矩形zoom 到覆盖它所需的最小尺寸&S容器

如何在模块层面提供服务?

您能在卸载程序(QtInsteller框架)上添加WizardPage吗?

这个值总是返回未定义的-Reaction

使用领域Web SDK的Vite+Vue应用程序中的Web程序集(WASM)错误

400 bad request error posting through node-fetch

为什么可选参数的顺序会导致问题?

从逗号和破折号分隔的给定字符串中查找所有有效的星期几

处理TypeScrip Vue组件未初始化的react 对象

MongoDB中的嵌套搜索

有没有办法更改Chart.js 3.x.x中主要刻度的字体?

重新呈现-react -筛选数据过多

使用CEPRESS截取时,cy.Wait()在等待5000ms的第一个路由请求时超时