我正在尝试为我的简单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();
});
});任何关于我如何解决这个问题的建议都是非常感谢的。
发布于 2020-01-17 09:35:38
请确保项目中安装了正确的类型。即
npm i -D @testing-library/jest-dom@^4.2.4
根据我的经验,5.x版似乎缺少类型类型
发布于 2020-05-06 13:12:02
这里的大多数答案似乎主要是关于巴别的。使用其他任何东西,如eslint、tslint等和纯类型文本,都足以将@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'如果使用纯require()或不同的配置,也可以使用JavaScript。
另一种选择(对于TypeScript,或者如果您不喜欢添加setupTests.js)是添加globals.d.ts (在我的例子中是项目根目录),并在那里添加上面的行(import ...)。
Note:这两种解决方案都可以在没有设置esModuleInterop的情况下工作。
https://stackoverflow.com/questions/57861187
复制相似问题