How to fix typescript error 'name' does not exist in type 'ByRoleOptions' when querying by accessible name using getByRole in react-testing-library
Sophia Terry
I have a component that renders a list of filters as removable chips which I am trying to test using react-testing-library. I am trying to do query by accessible name as explained here using getByRole.
component:
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:
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();
});But I am getting a typescript error:
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'How do I fix this?
I tried a couple of things to fix this. I imported getByRole directly from @testing-library/dom and deconstructed container from rendered component
const { container } = render(<FilterChips {...props} />);
and then tried to do query by accessible name as following
const PersonFilter = getByRole(container, 'filter-chip', { name: '${filters.people[0].Name} (${filters.people[0].Id})' });But this is also throwing the same error. Why am I getting this error and how do I fix it?
12 Answers
You can simply ignore ts preceding the problematic line with:
//@ts-ignore
const PersonFilter = getByRole('filter-chip', { name: `${filters.people[0].Name} (${filters.people[0].Id})` });This will ignore all typescript alerts and treat that next line as if it were plain javascript
following this example in the docs (scroll to the end of the section linked and click on the 'React' tab):
import { render } from '@testing-library/react'
const { getByRole } = render(<MyComponent />)
const dialogContainer = getByRole('dialog')your code should be:
const { getByRole } = render(<FilterChips {...props} />);
const PersonFilter = getByRole(`${filters.people[0].Name} (${filters.people[0].Id})`); 1