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

使用React Native Testing Library按accessibility role获取元素断言报错如何解决

解决方案

你遇到的问题可通过以下步骤逐一修复:

1. 修复组件属性语法错误

你的Text组件属性写法存在语法问题,且React Native中建议使用标准无障碍属性accessibilityRole来标记角色,同时遍历渲染必须加唯一key属性避免运行时报错,修复后的组件代码如下:

const [state, setState] = React.useState([]);
React.useEffect(() => {
  fetch("https://jsonplaceholder.typicode.com/todos/")
    .then((response) => response.json())
    .then((json) => setState(json));
}, []);

return (
  <View style={styles.container}>
    {state.map((i) => (
      <Text key={i.id} accessibilityRole="header">{i.title}</Text>
    ))}
  </View>
);
}

2. 修复测试逻辑问题

核心错误点:

  • 未Mock接口请求,直接调用线上接口会导致测试不稳定、异步时序不匹配
  • getByA11yRole是同步查询方法,等待异步渲染需要使用异步的findByA11yRole方法
  • 断言对象错误:你直接对组件实例做文本断言,需要先取到组件的文本内容
  • 断言方法使用错误:匹配正则需要用toMatch,toBe仅用于全等匹配
  • 若持续报toBe is not function错误,需要检查是否正确安装引入了@testing-library/jest-native扩展包,在测试入口文件引入import '@testing-library/jest-native/extend-expect'即可

修复后的测试代码:

import React from 'react';
import { render, cleanup } from '@testing-library/react-native';
import Json from './Json';

// Mock全局fetch方法,返回固定测试数据
global.fetch = jest.fn(() =>
  Promise.resolve({
    json: () => Promise.resolve([{ id: 1, title: 'delectus aut autem' }]),
  })
);

describe('<Json/>', () => {
  afterEach(cleanup);
  beforeEach(() => {
    fetch.mockClear();
  });

  test('get data properly', async () => {
    render(<Json/>);
    // 异步查询对应角色且内容匹配的组件
    const header = await findByA11yRole('header', { name: /delectus aut autem/ });
    // 二次验证组件文本内容
    expect(header.children[0]).toMatch(/delectus aut autem/);
    // 验证接口确实被调用
    expect(fetch).toHaveBeenCalledTimes(1);
  });
});

内容的提问来源于stack exchange,提问作者user12494839

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 06:54:05