`waitFor` doesn't advance time when using `jest` fake timers without injecting globals
-
@testing-library/domversion:9.3.4 - Testing Framework and version:
[email protected] - DOM Environment:
[email protected]
Relevant Code or Config:
A minimal sandbox to reproduce the issue is available on codesandbox. You can execute tests by opening a terminal and running the yarn test command.
Actions Undertaken:
- Configured
jestto not inject globals (--injectGlobals=false); refer to thepackage.jsoncommand from the sandbox above. - Created tests that rely on
waitFororwaitForElementToBeRemoved.
Outcome:
-
waitFornever advances timers by time (the default50msinterval of the loop or any other interval), causing the tests to exceed their timeout.
Reproduction:
You can reproduce this issue via the following codesandbox link.
Problem Description:
When using jest, but without injecting globals, the waitFor logic:
- Fails to identify
jest's environment in thejestFakeTimersAreEnabledpredicate. - Assuming the above was passing correctly, it would reference the
jestglobal object, which is undefined when not injecting globals. This would lead to an error when attempting to invokejest.advanceTimersByTime.
On a broader scope (although I want to keep this issue's focus narrow for the sake of actionability), there might be other unintended implicit assumptions about depending on (a) jest and / or (b) a test environment that injects globals. The following issues are related, although they focus on different manifested problems:
- https://github.com/testing-library/react-testing-library/issues/1240
- https://github.com/testing-library/react-testing-library/issues/1257
Suggested Solution:
- The first part of the issue (i.e.,
jestenvironment detection) can be resolved by adding anORcondition to thejestFakeTimersAreEnabledpredicate. In my experience, we should add a check forprocess.env.JEST_WORKER_IDto not beundefined. - The second issue could be addressed by dynamically attempting to import
jestfrom@jest/globalswhen (a) we detect aJEST_WORKER_IDand (b) we know fake timers are enabled.- I don't believe
dom-testing-libraryshould depend on@jest/globals. - I'm not completely satisfied with the tentative dynamic import of an optional dependency
@jest/globalsin this case, but I think it might provide the best developer experience for end users.
- I don't believe
Depending on the appetite for this issue to be fixed, I might work on a PR to address the above. I am somewhat surprised this hasn't come up before, but I guess not many people tend to set up jest without injecting globals.
@signorettif May this ussue be relative to this problem? https://github.com/testing-library/user-event/issues/1173
Yes! I think that's a symptom of the same underlying problem