Description
@testing-library/react
version: 12.1.2- Testing Framework and version: jest 26.6.0
- DOM Environment: jsdom 16.7.0
Relevant code or config:
const navigation = screen.getByRole("navigation");
let breadcrumbs = within(navigation);
expect(breadcrumbs.getByRole("link", { name: /home/i })).toBeInTheDocument();
// TS error here
breadcrumbs = within(navigation);
What you did:
I am learning TypeScript and have converted a React project including all tests.
What happened:
When attempting to reassign a variable using within
I am getting a TS error.
Reproduction:
Problem description:
This is very strange as it looks like the two calls to within
are returning a different type. I asked for help in the Testing Library Discord channel and was pointed at the Discord TypeScript channel where I received this response:
https://discord.com/channels/508357248330760243/746024503817011220/898609497206063124
That is quite strange. It looks like it's inferring with a slightly different generic prop in the two different cases. The first call infers as within<typeof import("file:///node_modules/@testing-library/dom/types/queries")>(/.../), the second as within(/.../).
I would expect those to be the same thing, but perhaps not.
The mechanism where it's inferring differently is probably because in the second case TS is using the known type of breadcrumbs to guide the inference.
... but I'm not sure how that would lead it to something that's incompatible with what it got in the first place.
FWIW, I copied this over into my project and am not getting this errors, so maybe it's a bug introduced into the typings recently?
Suggested solution:
One solution is to use any
:
const navigation = screen.getByRole("navigation");
let breadcrumbs: any = within(navigation);
expect(breadcrumbs.getByRole("link", { name: /home/i })).toBeInTheDocument();
breadcrumbs = within(navigation);
Another is to use a different variable altogether.
const navigation = screen.getByRole("navigation");
const breadcrumbs1 = within(navigation);
expect(breadcrumbs.getByRole("link", { name: /home/i })).toBeInTheDocument();
const breadcrumbs2 = within(navigation);
Being new to TypeScript I have no idea what is going on here or how to fix it properly.