首页 > 解决方案 > 如果我不导入它,为什么我可以使用来自“@testing-library/jest-dom”的expect expect().toBeInTheDocument?

问题描述

我使用“create React App”创建了一个 React.js 应用程序,并且我正在学习运行测试。

expect().toBeInTheDocument如果我不导入,为什么在下面的代码中可以使用@testing-library/jest-dom

import {render, screen} from "@testing-library/react";
import Greeting from "./Greeting";

test("renders Hello World as a text", () => {
    
    render(<Greeting/>);    
    const helloWorld = screen.getByText('Hello World');
    expect(helloWorld).toBeInTheDocument

});

标签: reactjsjestjsreact-testing-libraryjest-dom

解决方案


当您运行create react app它时,它会在您的目录中创建一个名为setup-test.js(或者.ts如果您使用 TypeScript)的文件,该文件会在那里src导入 @testing-library/jest-dom

此文件由 jestcreate-react-app在运行测试之前加载(配置为这样做)(我假设使用配置setupFiles


推荐阅读