我正在尝试为我的简单 React 应用程序编写测试,该应用程序使用 API 等为狗收容所创建 UI。我已经导入了如下所示的模块并运行了以下命令
npm install jest-dom react-testing-library --save-dev
但是,我得到了 toBeInTheDocument();红色下划线的方法和错误信息
"Property 'toBeInTheDocument' does not exist on type 'Matchers<any>'."
import "react-testing-library/cleanup-after-each";
import "jest-dom/extend-expect";
import * as React from "react";
import PetCard from "./PetCard";
import Pet from "./Pet";
import { render } from "react-testing-library";
const petMock = {
id: "225c5957d7f450baec75a67ede427e9",
name: "Fido",
status: "available",
kind: "dog",
breed: "Labrador",
} as Pet;
describe("PetCard", () => {
it("should render the name", () => {
const { getByText } = render(<PetCard pet={petMock} />);
expect(getByText("Fido")).toBeInTheDocument();
});
});
如有任何关于如何解决此问题的建议,我们将不胜感激。
最佳答案
这里的大多数答案似乎主要针对 Babel。如果你不使用 Babel,将 @testing-library/jest-dom
添加到你的类型中就足够了。
所以几个快速的步骤:
确保你已经安装了库:
yarn add -D @testing-library/jest-dom
或
npm i @testing-library/jest-dom --save-dev
然后将其链接到您的 tsconfig.json:
"types": ["node", "jest", "@testing-library/jest-dom"],
现在我们来处理 Jest 配置。与其在每个测试文件中导入它,不如在 Jest 配置文件中导入它(通常称为 jest.config.js):
setupFilesAfterEnv: [
"<rootDir>/support/setupTests.js"
],
然后在文件 setupTests.js
中:
import '@testing-library/jest-dom/extend-expect'
如果使用纯 JavaScript 或不同的配置,则使用 require()
。
另一种方法(对于 TypeScript 或者如果您不喜欢添加 setupTests.js)是添加 globals.d.ts
(在我的例子中添加到项目根目录目录)并添加上面的行(import ...
)。
注意:这两种解决方案都可以设置esModuleInterop
。
注意:如果使用 TypeScript,请使用 npm install @types/testing-library__jest-dom -D
关于reactjs - 类型 'toBeInTheDocument' 上不存在属性 'Matchers<any>',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57861187/