expect(...).toHaveAttribute 不是函数 - 为什么?

expect(...).toHaveAttribute is not a function - Why?

我创建了一些基本测试并遵循了 Jests 网站上的入门指南,但 toHaveAttribute 显然不是一个函数

import React from "react";
import { fireEvent, render } from "@testing-library/react";
import userEvent from "@testing-library/user-event";

import { App } from "../App";

test("allows users to add items to their list", () => {
  const { getByText, getByLabelText, getByTestId } = render(<App />);

  const input = getByLabelText("What needs to be done?");
  userEvent.type(getByTestId("email"), "Hello World!")
  expect(getByTestId("email")).toHaveAttribute("value", "Hello, World!")
})

TypeError: expect(...).toHaveAttribute 不是函数

  10 |   const input = getByLabelText("What needs to be done?");
  11 |   userEvent.type(getByTestId("email"), "Hello World!")
> 12 |   expect(getByTestId("email")).toHaveAttribute("value", "Hello, World!")
     |                                ^
  13 | })

我完全按照教程进行操作,所以我不确定为什么会这样。

方法 toHaveAttributejest-dom 的一部分,可以测试 DOM 元素。您需要验证您是否已在您的项目中正确设置它。

安装模块:

npm install --save-dev @testing-library/jest-dom

之后,您可以像推荐的那样在您的 jest 设置文件中包含:

// In your own jest-setup.js (or any other name)
import '@testing-library/jest-dom'

// In jest.config.js add (if you haven't already)
setupFilesAfterEnv: ['<rootDir>/jest-setup.js']