Skip to content

Provide a way to find out whether fake timers have been enabled. #10555

@9still

Description

@9still

🚀 Feature Proposal

Provide a method (e.g. jest.usingFakeTimers()) that returns true if jest.useFakeTimers was previously invoked. Alternatively, a property or a config object could be exposed with the same information.

Motivation

It is often convenient to have a global cleanup routine for tests that does things like always reverting to real timers, etc. It would be awesome if we could flush timers (e.g. jest.runOnlyPendingTimers()) in this cleanup routine as well, but to do that, one would need to find out if fake timers are actually being used.

There are already examples of libraries resorting to introspection of the setTimeout implementation to try to deduce this for similar purposes.

@kentcdodds had to do the following https://github.com/testing-library/react-testing-library/pull/720/files recently

function getIsUsingFakeTimers() {
  return (
    typeof jest !== 'undefined' &&
    typeof setTimeout !== 'undefined' &&
    (setTimeout.hasOwnProperty('_isMockFunction') ||
      setTimeout.hasOwnProperty('clock'))
  )
}

Would be awesome if jest exposed an official method to check the above, so that tooling wouldn't break if the underlying implementation were to change.

Example

afterEach(() => {
  if (jest.usingFakeTimers()) {
    jest.runOnlyPendingTimers();
  }
});

Pitch

Why does this feature belong in the Jest core platform?

Since jest.useFakeTimers is a part of the core platform, it seems reasonable to be able to find out whether that call had previously been invoked. The core platform is the only place that would be able to provide this information.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions