React Native测试报错:无法找到@testing-library/jest-native模块
解决React Native测试中找不到@testing-library/jest-native的问题
1. 安装缺失的依赖
toHaveStyle断言属于@testing-library/jest-native包,而非@testing-library/react-native,你需要先安装这个依赖:
npm install --save-dev @testing-library/jest-native # 或使用yarn yarn add -D @testing-library/jest-native
2. 全局配置断言扩展
无需在单个测试文件里手动扩展断言,直接在jest.setup.js中全局引入,让所有测试文件都能使用这些断言:
修改jest.setup.js,添加以下代码:
import '@testing-library/jest-native/extend-expect';
3. 简化测试文件代码
移除测试文件中手动导入和扩展toHaveStyle的代码,直接使用断言即可:
import React from 'react'; import { render } from '@testing-library/react-native'; import JobForm from '../JobForm'; describe('JobForm', () => { it('应包含指定样式', () => { const { getByTestId } = render(<JobForm />); const targetElement = getByTestId('job-form-input'); expect(targetElement).toHaveStyle({ backgroundColor: '#f5f5f5', borderRadius: 8, }); }); });
4. 验证Jest配置有效性
确认package.json中的Jest配置已正确引入jest.setup.js,你的现有配置已经满足要求,无需额外调整。
内容的提问来源于stack exchange,提问作者dnd1993
相关产品推荐
相关产品推荐

