我有一个组件将过滤器列表呈现为可移动芯片,我正在尝试使用 react-testing-library 对其进行测试.我正在尝试按解释的可访问名称进行查询 here使用 getByRole
.
组件:
import Chip from '@material-ui/core/Chip';
import PersonIcon from '@material-ui/icons/Person';
import React from 'react';
import './FilterChips.less';
import { Filters } from './types';
export type FilterChipsProps = {
filters: Filters,
};
export const FilterChips = (props: FilterChipsProps) => {
const { filters } = props;
const people = filters.people
? filters.people.map((person: any) => (
<Chip
icon={<PersonIcon />}
label={`${person.Name} (${person.Id})`}
key={person.Id}
className='chips'
role='filter-chip'
/>
))
: [];
return people.length > 0
? (
<div className='filters'>
<span>Filters: </span>
{people}
</div>
)
:
null;
};
测试:
test('that filters are rendered properly', async () => {
const filters = {
people: [
{ Id: '1', Name: 'Hermione Granger' },
{ Id: '2', Name: 'Albus Dumbledore' },
],
};
const props = { filters };
const { getByRole } = render(<FilterChips {...props} />);
const PersonFilter = getByRole('filter-chip', { name: `${filters.people[0].Name} (${filters.people[0].Id})` });
expect(PersonFilter).toBeDefined();
});
但是我遇到了 typescript 错误:
Argument of type '{ name: string; }' is not assignable to parameter of type 'ByRoleOptions'.
Object literal may only specify known properties, and 'name' does not exist in type 'ByRoleOptions'
我该如何解决这个问题?
我尝试了一些方法来解决这个问题。我导入了getByRole
直接来自 @testing-library/dom
和解构container
来自渲染组件
const { container } = render(<FilterChips {...props} />);
然后尝试按以下可访问的名称进行查询
const PersonFilter = getByRole(container, 'filter-chip', { name: '${filters.people[0].Name} (${filters.people[0].Id})' });
但这也抛出同样的错误。为什么会出现此错误以及如何解决?
最佳答案
您可以简单地忽略有问题的行之前的 ts:
//@ts-ignore
const PersonFilter = getByRole('filter-chip', { name: `${filters.people[0].Name} (${filters.people[0].Id})` });
这将忽略所有 typescript 警报并将下一行视为纯 javascript
关于reactjs - 在 react-testing-library 中使用 getByRole 按可访问的名称查询时,如何修复 typescript 错误 'name' 在类型 'ByRoleOptions' 中不存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60701871/
相关文章:
python-3.x - 在 python 中更快地读取大型 xlsb 文件
tensorflow - 转换后的 Tensorflow JS 模型报告缺少输入形状
image - Flutter web Image.network旋转图片
javascript - Vue CLI - 未找到 PostCSS 配置
react-native - React Native 风格 textDecorationLine
c++ - 这是带有 std::any 或 std::is_copy_constructible 的
npm - 错误 : pngquant failed to build, 确保安装了 libpng-
typescript - 如何在 WebStorm/IntelliJ 中使用 ts-node 导入项