You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 23:55:18