即使没有显式导入expect
函数,你仍然可以在测试文件中使用expect().toBeInTheDocument()
,这是因为Jest和相关的库(如@testing-library/jest-dom
)在全局作用域中提供了expect
函数。这种设计是为了简化测试代码的编写,让开发者不需要每次都导入expect
。
toBeInTheDocument
就是其中之一。expect
函数可以使测试代码更加简洁明了。如果你在使用expect().toBeInTheDocument()
时遇到问题,可能是因为以下原因:
@testing-library/jest-dom
:确保你已经通过npm或yarn安装了这个库,并且在Jest配置中添加了它作为测试环境的一部分。@testing-library/jest-dom
:确保你已经通过npm或yarn安装了这个库,并且在Jest配置中添加了它作为测试环境的一部分。jest.config.js
)中添加:jest.config.js
)中添加:setupTests.js
文件,内容如下:setupTests.js
文件,内容如下:expect
是在全局作用域中定义的。@testing-library/jest-dom
版本是兼容的。以下是一个简单的测试示例,展示了如何使用expect().toBeInTheDocument()
:
import React from 'react';
import { render, screen } from '@testing-library/react';
import MyComponent from './MyComponent';
test('renders learn react link', () => {
render(<MyComponent />);
const linkElement = screen.getByText(/learn react/i);
expect(linkElement).toBeInTheDocument();
});
在这个例子中,即使我们没有导入expect
,它仍然可以在测试中使用,因为@testing-library/jest-dom
已经为我们做好了全局配置。
领取专属 10元无门槛券
手把手带您无忧上云