testing-library / dom-testing-library

🐙 Simple and complete DOM testing utilities that encourage good testing practices.
https://testing-library.com/dom
MIT License
3.27k stars 467 forks source link

feat: Improve performance of findBy*/findAllBy* by not generating informative error messages #1071

Open timjb opened 3 years ago

timjb commented 3 years ago

What: Improve performance of findBy/findAllBy by not generating informative error messages in the function passed to waitFor. The work of generating these error messages almost entirely wasted because all of them, except possibly the last one (if the test is red), will be discarded by waitFor. Instead, if the call to waitFor failed, another attempt to find the element(s) is made, this time generating a useful error message if it also fails.

Why: I've noticed that in the codebase I am working on, significant CPU time is spent generating useful error messages that are later discarded. In particular, I've found that in one particular test suite the function prettyDOM takes approximately ~100ms per execution. (The tested React component has a lot of DOM nodes since it embeds an instance of AG Grid.)

How: I've added a second argument to makeFindQuery which is supposed to be a getter function just like the first argument, but may not provide useful error messages in the case of failure, which is used in the call to waitFor. For backwards compatibility I'm using the first argument as a default. If the call to waitFor fails, then the first argument is used instead.

Checklist:

Alternative: This PR implements just one possible approach to avoid the unnecessary work of generating informative error messages only for them to be discarded later. Another approach could build on _disableExpensiveErrorDiagnostics (introduced in #590):

One advantage of this alternate approach would be that this would also decrease CPU usage when using getBy/getAllBy inside waitFor, like in the following code:

await waitFor(() => {
  expect(getByTestId("foo")).toHaveAttribute("href", "https://example.com");
});
codesandbox-ci[bot] commented 3 years ago

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

Latest deployment of this branch, based on commit b81a964ee7a1e5e0a0c98518a32313e28770562c:

Sandbox Source
react-testing-library-examples Configuration