使用React Testing Library如何检测返回值中导入的组件是否存在于文档中
解决方案
方案1:通过data-testid查询(推荐,符合黑盒测试逻辑)
在Plans组件引用HelloComponent时添加测试ID属性:
import HelloComponent from './helloComponent'; const Plans: FC = () => { return ( <div> <HelloComponent data-testid="hello-component" /> </div> ); }; export default Plans;
测试代码中直接查询该测试ID判断是否存在:
import { screen } from '@testing-library/react'; describe('plans', () => { it('renders the plans component', async () => { render(<Plans />); // 校验HelloComponent是否存在于文档中 expect(screen.getByTestId('hello-component')).toBeInTheDocument(); });
提示:如果运行时提示
toBeInTheDocument不存在,请确保你已安装@testing-library/jest-dom并在测试入口文件中全局导入。
方案2:模拟子组件校验渲染状态(适合纯单元测试,无需修改业务代码)
在测试文件顶部先模拟HelloComponent组件:
// 模拟路径需和业务代码中导入HelloComponent的路径完全一致 jest.mock('./helloComponent', () => ({ __esModule: true, default: jest.fn(() => <div data-testid="mock-hello-component" />), })); describe('plans', () => { it('renders the plans component', async () => { render(<Plans />); // 方式1:查询模拟组件的测试ID expect(screen.getByTestId('mock-hello-component')).toBeInTheDocument(); // 方式2:直接校验模拟组件是否被调用 const MockHelloComponent = jest.requireMock('./helloComponent').default; expect(MockHelloComponent).toHaveBeenCalledTimes(1); });
内容的提问来源于stack exchange,提问作者HelloL
相关产品推荐
相关产品推荐

