Description
(this issue has been edited to reflect an updated intent; it was originally a proposal to change prefer-presence-queries
)
Name for new rule
prefer-query-matchers
Description of the new rule
The rule should somehow provide a way to enforce that toBeVisible()
should always be called with a getBy*
query in place of a queryBy*
. This works differently than the prefer-presence-queries
rule, because a negative there expects an element to not be present in the DOM. In my understanding not.toBeVisible()
means "is present in the DOM but is not visible," and it fails if it receives a null: "received value must be an HTMLElement or an SVGElement".
Rather than coding for this specific matcher only, we currently plan to provide a configurable rule where you can configure which matchers require get
and which require query
.
Testing Library feature
The getBy*
and queryBy*
queries. It is prompted by the toBeVisible
matcher from jest-dom
.
Testing Library frameworks
getBy*
and queryBy*
are in the Core API and so are not specific to any framework.
What category of rule is this?
Other: a best-practice recommendation. It allows users to configure rules to enforce use of the queries that will produce the best failure messages.
Code Examples
For the following proposed options schema:
{
"rules": {
"prefer-query-matchers": ["error", {
"validEntries": [{ "query": "get", "matcher": "toBeVisible"}]
}],
}
}
With the following code:
/* 1 */ expect(screen.queryByText("a")).toBeVisible();
/* 2 */ expect(screen.getByText("a")).toBeVisible();
/* 3 */ expect(screen.queryByText("a")).not.toBeVisible();
/* 4 */ expect(screen.getByText("a")).not.toBeVisible();
1 and 3 would produce errors, and 2 and 4 would not.
If instead the query
value was changed:
{
"validEntries": [{ "query": "get", "matcher": "toBeVisible"}]
}
Then 2 and 4 would produce errors, and 1 and 3 would not.
Anything else?
We investigated handling this with the existing prefer-presence-queries
rule, but since that rule has a presence/absence distinction and the motivating case toBeVisible
does not, it is a better fit to handle it in its own standalone rule. That also allows users to configure handling for any number of matchers.
Do you want to submit a pull request to change the rule?
Yes