首页 > 解决方案 > 使用本机测试库难以找到元素

问题描述

我对使用 react-testing-library 非常陌生,特别是 native-testing-library。我似乎在查询元素时遇到了麻烦。

在下面的示例中,我希望测试通过,但似乎找不到元素。

我有一种感觉,我在某处做错了什么,但我找不到太多关于它的信息。任何帮助都将不胜感激[:

编辑** 如果我使用 TestID 似乎工作正常,但我不应该仍然能够通过文本评论查询它吗?除非绝对必要,否则我不喜欢使用测试 ID,因为它不是面向用户的。

这是我要测试的组件

import React from 'react';
import {Text, View} from 'react-native';
import {GITHUB_COLORS} from '../constants/colors';
import styles from './RepoCard.style';
import truncate from '../utilities/truncate';

function RepoCard({repo}) {
  return (
    <View style={styles.card}>
      {repo && (
        <>
          <Text style={styles.title}>{truncate(25, repo.name)}</Text>
          {repo.description && (
            <Text style={styles.description}>
              {truncate(60, repo.description)}
            </Text>
          )}
          {repo.language && (
            <View style={styles.langauge}>
              <View
                style={[
                  styles.languageColor,
                  {
                    backgroundColor: GITHUB_COLORS[repo.language.toLowerCase()],
                  },
                ]}
              />
              <Text style={styles.text}>{repo.language}</Text>
            </View>
          )}
        </>
      )}
    </View>
  );
}

export default RepoCard;

这是测试文件

import React from 'react';
import {render, wait} from '@testing-library/react-native';
import RepoCard from './RepoCard';
import {REPOS} from '../testing/mocks/repos';

test('displays the repo name', async () => {
  const testRepo = REPOS[0];
  const {queryByText} = render(<RepoCard repo={testRepo} />);
  const name = testRepo.name;

  await wait(() => expect(queryByText(name)).toBeTruthy());
});

最后是 repo 对象,我仔细检查了它,它需要的所有东西都应该在里面。

export const REPOS = [
  {
    name: 'AndroidPython3',
    language: 'Python',
    description: 'This is a mock description',
  },
  {
    name: 'arduino-i2c-scanner',
    language: 'C++',
    description: 'Simple Arduino I2C scanner as des',
  },
];

我还为此创建了一个代码沙箱,尽管我认为它实际上不能运行测试,因为它使用了 react-native-web。

https://codesandbox.io/s/gallant-tereshkova-3biqj

标签: reactjsreact-nativereact-testing-libraryreact-native-testing-library

解决方案


我想通了,我在开玩笑的配置中错过了以下内容

+ preset: '@testing-library/react-native'
- preset: 'react-native'

推荐阅读