Testing library `within` return type in typescript

41 Views Asked by At

I have the following helpers for my tests with React & testing library :

const getSomething = (name: string, container: Screen | any = screen) {
  return container.getByRole('someRole', { name: name })
}

The container is either the screen from react testing, but it can also come from testing library :

const myParentElement = screen.getByRole('cell', { name: 'foo' })
const myElement = getSomething("myName", within(myParentElement))

How can I replace the any from container: Screen | any with the appropriate type returned by within ?

Note: within is an alias for getQueriesForElement, which is defined here on testing-library

1

There are 1 best solutions below

0
Lin Du On BEST ANSWER

As @jayatubi metioned, ReturnType<typeof within> should work.

import { within, screen, Screen } from '@testing-library/react';

const getSomething = (name: string, container: Screen | ReturnType<typeof within> = screen) => {
  return container.getByRole('someRole', { name: name });
};

const myParentElement = screen.getByRole('cell', { name: 'foo' });
const myElement = getSomething('myName', within(myParentElement));

package version:

"@testing-library/react": "^14.1.2",
"typescript": "^5.3.2",