Fix frontend test assertions - remove inaccessible form role checks

- Update login-form.test.tsx to remove screen.getByRole('form') assertions
- Tests now check for form elements directly by label text
This commit is contained in:
Denis Urs Rudolph
2026-04-06 22:18:06 +02:00
parent 23dab73bd8
commit 9122eeff9d
2724 changed files with 345785 additions and 3 deletions
+11
View File
@@ -0,0 +1,11 @@
Copyright (c) 2010-2014, Christian Johansen, christian@cjohansen.no. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+428
View File
@@ -0,0 +1,428 @@
# `@sinonjs/fake-timers`
[![codecov](https://codecov.io/gh/sinonjs/fake-timers/branch/main/graph/badge.svg)](https://codecov.io/gh/sinonjs/fake-timers)
<a href="CODE_OF_CONDUCT.md"><img src="https://img.shields.io/badge/Contributor%20Covenant-v2.0%20adopted-ff69b4.svg" alt="Contributor Covenant" /></a>
JavaScript implementation of the timer
APIs; `setTimeout`, `clearTimeout`, `setImmediate`, `clearImmediate`, `setInterval`, `clearInterval`, `requestAnimationFrame`, `cancelAnimationFrame`, `requestIdleCallback`,
and `cancelIdleCallback`, along with a clock instance that controls the flow of time. FakeTimers also provides a `Date`
implementation that gets its time from the clock.
In addition in browser environment `@sinonjs/fake-timers` provides a `performance` implementation that gets its time
from the clock. In Node environments FakeTimers provides a `nextTick` implementation that is synchronized with the
clock - and a `process.hrtime` shim that works with the clock.
`@sinonjs/fake-timers` can be used to simulate passing time in automated tests and other
situations where you want the scheduling semantics, but don't want to actually
wait.
`@sinonjs/fake-timers` is an integral part of [Sinon.JS](https://github.com/sinonjs/sinon.js) and targets
the [same runtimes](https://sinonjs.org/releases/latest#compatibility-and-supported-runtimes).
## Autocomplete, IntelliSense and TypeScript definitions
`@sinonjs/fake-timers` ships with built-in type definitions generated from JSDoc. This provides autocomplete and type suggestions in supporting IDEs and TypeScript projects without requiring external `@types` packages.
## Installation
`@sinonjs/fake-timers` can be used in both Node and browser environments. Installation is as easy as
```sh
npm install @sinonjs/fake-timers
```
If you want to use `@sinonjs/fake-timers` in a browser you can either build your own bundle or
use [Skypack](https://www.skypack.dev).
## Usage
To use `@sinonjs/fake-timers`, create a new clock, schedule events on it using the timer
functions and pass time using the `tick` method.
```js
// In the browser distribution, a global `FakeTimers` is already available
var FakeTimers = require("@sinonjs/fake-timers");
var clock = FakeTimers.createClock();
clock.setTimeout(function () {
console.log(
"The poblano is a mild chili pepper originating in the state of Puebla, Mexico.",
);
}, 15);
// ...
clock.tick(15);
```
Upon executing the last line, an interesting fact about the
[Poblano](https://en.wikipedia.org/wiki/Poblano) will be printed synchronously to
the screen. If you want to simulate asynchronous behavior, please see the `async` function variants (
eg `clock.tick(time)` vs `await clock.tickAsync(time)`).
The `next`, `runAll`, `runToFrame`, and `runToLast` methods are available to advance the clock. See the
API Reference for more details.
### Faking the native timers
When using `@sinonjs/fake-timers` to test timers, you will most likely want to replace the native
timers such that calling `setTimeout` actually schedules a callback with your
clock instance, not the browser's internals.
Calling `install` with no arguments achieves this. You can call `uninstall`
later to restore things as they were again.
Note that in NodeJS the [timers](https://nodejs.org/api/timers.html)
and [timers/promises](https://nodejs.org/api/timers.html#timers-promises-api) modules will also receive fake timers when
using global scope.
```js
// In the browser distribution, a global `FakeTimers` is already available
var FakeTimers = require("@sinonjs/fake-timers");
var clock = FakeTimers.install();
// Equivalent to
// var clock = FakeTimers.install(typeof global !== "undefined" ? global : window);
setTimeout(fn, 15); // Schedules with clock.setTimeout
clock.uninstall();
// setTimeout is restored to the native implementation
```
To hijack timers in another context pass it to the `install` method.
```js
var FakeTimers = require("@sinonjs/fake-timers");
var context = {
setTimeout: setTimeout, // By default context.setTimeout uses the global setTimeout
};
var clock = FakeTimers.withGlobal(context).install();
context.setTimeout(fn, 15); // Schedules with clock.setTimeout
clock.uninstall();
// context.setTimeout is restored to the original implementation
```
Usually you want to install the timers onto the global object, so call `install`
without arguments.
#### Automatically incrementing mocked time
FakeTimers supports the possibility to attach the faked timers to any change
in the real system time. This means that there is no need to `tick()` the
clock in a situation where you won't know **when** to call `tick()`.
Please note that this is achieved using the original setImmediate() API at a certain
configurable interval `config.advanceTimeDelta` (default: 20ms). Meaning time would
be incremented every 20ms, not in real time.
An example would be:
```js
var FakeTimers = require("@sinonjs/fake-timers");
var clock = FakeTimers.install({
shouldAdvanceTime: true,
advanceTimeDelta: 40,
});
setTimeout(() => {
console.log("this just timed out"); //executed after 40ms
}, 30);
setImmediate(() => {
console.log("not so immediate"); //executed after 40ms
});
setTimeout(() => {
console.log("this timed out after"); //executed after 80ms
clock.uninstall();
}, 50);
```
In addition to the above, mocked time can be configured to advance more quickly
using `clock.setTickMode({ mode: "nextAsync" });`. With this mode, the clock
advances to the first scheduled timer and fires it, in a loop. Between each timer,
it will also break the event loop, allowing any scheduled promise
callbacks to execute _before_ running the next one.
## API Reference
### `var clock = FakeTimers.createClock([now[, loopLimit]])`
Creates a clock. The default
[epoch](https://en.wikipedia.org/wiki/Epoch_%28reference_date%29) is `0`.
The `now` argument may be a number (in milliseconds) or a Date object.
The `loopLimit` argument sets the maximum number of timers that will be run when calling `runAll()` before assuming that
we have an infinite loop and throwing an error. The default is `1000`.
### `var clock = FakeTimers.install([config])`
Installs FakeTimers using the specified config (otherwise with epoch `0` on the global scope).
Note that in NodeJS the [timers](https://nodejs.org/api/timers.html)
and [timers/promises](https://nodejs.org/api/timers.html#timers-promises-api) modules will also receive fake timers when
using global scope.
The following configuration options are available
| Parameter | Type | Default | Description |
| -------------------------------- | ----------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `config.now` | Number/Date | 0 | installs FakeTimers with the specified unix epoch |
| `config.toFake` | String[] | ["setTimeout", "clearTimeout", "setImmediate", "clearImmediate","setInterval", "clearInterval", "Date", "requestAnimationFrame", "cancelAnimationFrame", "requestIdleCallback", "cancelIdleCallback", "hrtime", "performance"] | an array with explicit function names (or objects, in the case of "performance") to hijack. When not set, FakeTimers will automatically fake all methods e.g., `FakeTimers.install({ toFake: ["setTimeout","nextTick"]})` will fake only `setTimeout` and `nextTick`. Cannot be combined with `config.toNotFake`. |
| `config.toNotFake` | String[] | [] | an array with explicit function names that should remain native. When set, FakeTimers will fake every other supported method e.g., `FakeTimers.install({ toNotFake: ["Date"] })` fakes all supported methods except `Date`. Cannot be combined with `config.toFake`. |
| `config.loopLimit` | Number | 1000 | the maximum number of timers that will be run when calling runAll() |
| `config.shouldAdvanceTime` | Boolean | false | tells FakeTimers to increment mocked time automatically based on the real system time shift (e.g. the mocked time will be incremented by 20ms for every 20ms change in the real system time) |
| `config.advanceTimeDelta` | Number | 20 | relevant only when using with `shouldAdvanceTime: true`. increment mocked time by `advanceTimeDelta` ms every `advanceTimeDelta` ms change in the real system time. |
| `config.shouldClearNativeTimers` | Boolean | false | tells FakeTimers to clear 'native' (i.e. not fake) timers by delegating to their respective handlers. These are not cleared by default, leading to potentially unexpected behavior if timers existed prior to installing FakeTimers. |
| `config.ignoreMissingTimers` | Boolean | false | tells FakeTimers to ignore missing timers that might not exist in the given environment |
### `clock.setTickMode(mode)`
Allows configuring how the clock advances time, automatically or manually.
There are 3 different types of modes for advancing timers:
- `{mode: 'manual'}`: Timers do not advance without explicit, manual calls to the tick
APIs (`clock.nextAsync`, `clock.runAllAsync`, etc). This mode is equivalent to `false`.
- `{mode: 'nextAsync'}`: The clock will continuously break the event loop, then run the next timer until the mode changes.
As a result, tests can be written in a way that is independent from whether fake timers are installed.
Tests can always be written to wait for timers to resolve, even when using fake timers.
- `{mode: 'interval', delta?: <number>}`: This is the same as specifying `shouldAdvanceTime: true` with an `advanceTimeDelta`. If the delta is
not specified, 20 will be used by default.
The 'nextAsync' mode differs from `interval` in two key ways:
1. The microtask queue is allowed to empty between each timer execution,
as would be the case without fake timers installed.
1. It advances as quickly and as far as necessary. If the next timer in
the queue is at 1000ms, it will advance 1000ms immediately whereas interval,
without manually advancing time in the test, would take `1000 / advanceTimeDelta`
real time to reach and execute the timer.
### `var id = clock.setTimeout(callback, timeout)`
Schedules the callback to be fired once `timeout` milliseconds have ticked by.
In Node.js `setTimeout` returns a timer object. FakeTimers will do the same, however
its `ref()` and `unref()` methods have no effect.
In browsers a timer ID is returned.
### `clock.clearTimeout(id)`
Clears the timer given the ID or timer object, as long as it was created using
`setTimeout`.
### `var id = clock.setInterval(callback, timeout)`
Schedules the callback to be fired every time `timeout` milliseconds have ticked
by.
In Node.js `setInterval` returns a timer object. FakeTimers will do the same, however
its `ref()` and `unref()` methods have no effect.
In browsers a timer ID is returned.
### `clock.clearInterval(id)`
Clears the timer given the ID or timer object, as long as it was created using
`setInterval`.
### `var id = clock.setImmediate(callback)`
Schedules the callback to be fired once `0` milliseconds have ticked by. Note
that you'll still have to call `clock.tick()` for the callback to fire. If
called during a tick the callback won't fire until `1` millisecond has ticked
by.
In Node.js `setImmediate` returns a timer object. FakeTimers will do the same,
however its `ref()` and `unref()` methods have no effect.
In browsers a timer ID is returned.
### `clock.clearImmediate(id)`
Clears the timer given the ID or timer object, as long as it was created using
`setImmediate`.
### `clock.requestAnimationFrame(callback)`
Schedules the callback to be fired on the next animation frame, which runs every
16 ticks. Returns an `id` which can be used to cancel the callback. This is
available in both browser & node environments.
### `clock.cancelAnimationFrame(id)`
Cancels the callback scheduled by the provided id.
### `clock.requestIdleCallback(callback[, timeout])`
Queued the callback to be fired during idle periods to perform background and low priority work on the main event loop.
Callbacks which have a timeout option will be fired no later than time in milliseconds. Returns an `id` which can be
used to cancel the callback.
### `clock.cancelIdleCallback(id)`
Cancels the callback scheduled by the provided id.
### `clock.countTimers()`
Returns the number of waiting timers. This can be used to assert that a test
finishes without leaking any timers.
### `clock.hrtime(prevTime?)`
Only available in Node.js, mimicks process.hrtime().
### `clock.nextTick(callback)`
Only available in Node.js, mimics `process.nextTick` to enable completely synchronous testing flows.
### `clock.performance.now()`
Only available in browser environments, mimicks performance.now().
### `clock.tick(time)` / `await clock.tickAsync(time)`
Advance the clock, firing callbacks if necessary. `time` may be the number of
milliseconds to advance the clock by or a human-readable string. Valid string
formats are `"08"` for eight seconds, `"01:00"` for one minute and `"02:34:10"`
for two hours, 34 minutes and ten seconds.
The `tickAsync()` will also break the event loop, allowing any scheduled promise
callbacks to execute _before_ running the timers.
### `clock.next()` / `await clock.nextAsync()`
Advances the clock to the the moment of the first scheduled timer, firing it.
The `nextAsync()` will also break the event loop, allowing any scheduled promise
callbacks to execute _before_ running the timers.
### `clock.jump(time)`
Advance the clock by jumping forward in time, firing callbacks at most once.
`time` takes the same formats as [`clock.tick`](#clockticktime--await-clocktickasynctime).
This can be used to simulate the JS engine (such as a browser) being put to sleep and resumed later, skipping
intermediary timers.
### `clock.reset()`
Removes all timers and ticks without firing them, and sets `now` to `config.now`
that was provided to `FakeTimers.install` or to `0` if `config.now` was not provided.
Useful to reset the state of the clock without having to `uninstall` and `install` it.
### `clock.runAll()` / `await clock.runAllAsync()`
This runs all pending timers until there are none remaining. If new timers are added while it is executing they will be
run as well.
This makes it easier to run asynchronous tests to completion without worrying about the number of timers they use, or
the delays in those timers.
It runs a maximum of `loopLimit` times after which it assumes there is an infinite loop of timers and throws an error.
The `runAllAsync()` will also break the event loop, allowing any scheduled promise
callbacks to execute _before_ running the timers.
### `clock.runMicrotasks()`
This runs all pending microtasks scheduled with `nextTick` but none of the timers and is mostly useful for libraries
using FakeTimers underneath and for running `nextTick` items without any timers.
### `clock.runToFrame()`
Advances the clock to the next frame, firing all scheduled animation frame callbacks,
if any, for that frame as well as any other timers scheduled along the way.
### `clock.runToLast()` / `await clock.runToLastAsync()`
This takes note of the last scheduled timer when it is run, and advances the
clock to that time firing callbacks as necessary.
If new timers are added while it is executing they will be run only if they
would occur before this time.
This is useful when you want to run a test to completion, but the test recursively
sets timers that would cause `runAll` to trigger an infinite loop warning.
The `runToLastAsync()` will also break the event loop, allowing any scheduled promise
callbacks to execute _before_ running the timers.
### `clock.setSystemTime([now])`
This simulates a user changing the system clock while your program is running.
It affects the current time but it does not in itself cause e.g. timers to fire;
they will fire exactly as they would have done without the call to
setSystemTime().
### `clock.uninstall()`
Restores the original methods of the native timers or the methods on the object
that was passed to `FakeTimers.withGlobal`
### `Date`
Implements the `Date` object but using the clock to provide the correct time.
### `Performance`
Implements the `now` method of the [`Performance`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/now)
object but using the clock to provide the correct time. Only available in environments that support the Performance
object (browsers mostly).
### `FakeTimers.withGlobal`
In order to support creating clocks based on separate or sandboxed environments (such as JSDOM), FakeTimers exports a
factory method which takes single argument `global`, which it inspects to figure out what to mock and what features to
support. When invoking this function with a global, you will get back an object with `timers`, `createClock`
and `install` - same as the regular FakeTimers exports only based on the passed in global instead of the global
environment.
## Promises and fake time
If you use a Promise library like Bluebird, note that you should either call `clock.runMicrotasks()` or make sure to
_not_ mock `nextTick`.
## Running tests
FakeTimers has a comprehensive test suite. If you're thinking of contributing bug
fixes or suggesting new features, you need to make sure you have not broken any
tests. You are also expected to add tests for any new behavior.
### On node:
```sh
npm test
```
Or, if you prefer more verbose output:
```
$(npm bin)/mocha ./test/fake-timers-test.js
```
### In the browser
[Mochify](https://github.com/mochify-js) is used to run the tests in headless
Chrome.
```sh
npm test-headless
```
## License
BSD 3-clause "New" or "Revised" License (see LICENSE file)
## Contributing
`@sinonjs/fake-timers` uses JSDoc in `src/fake-timers-src.js` as the source of truth for its public types.
TypeScript declarations are automatically generated from this file. When contributing changes:
- Update JSDoc annotations in `src/fake-timers-src.js` if the public API changes.
- Run `npm run types:build` to regenerate the declarations in `types/`.
- Ensure `npm run types:smoke` still passes to validate the generated types.
- `tsgo` is used as a parallel validation lane to ensure compatibility with future TypeScript versions.
+91
View File
@@ -0,0 +1,91 @@
{
"name": "@sinonjs/fake-timers",
"description": "Fake JavaScript timers",
"version": "15.3.0",
"homepage": "https://github.com/sinonjs/fake-timers",
"author": "Christian Johansen",
"repository": {
"type": "git",
"url": "git+https://github.com/sinonjs/fake-timers.git"
},
"bugs": {
"mail": "christian@cjohansen.no",
"url": "https://github.com/sinonjs/fake-timers/issues"
},
"license": "BSD-3-Clause",
"scripts": {
"lint": "eslint .",
"test-node": "mocha --timeout 200 test/ integration-test/ -R dot --check-leaks",
"test-headless": "mochify --driver puppeteer",
"test-check-coverage": "npm run test-coverage && nyc check-coverage",
"test-cloud": "npm run test-edge && npm run test-firefox && npm run test-safari",
"test-edge": "BROWSER_NAME=MicrosoftEdge mochify --config mochify.webdriver.js",
"test-firefox": "BROWSER_NAME=firefox mochify --config mochify.webdriver.js",
"test-safari": "BROWSER_NAME=safari mochify --config mochify.webdriver.js",
"test-coverage": "nyc -x mochify.webdriver.js -x coverage --all --reporter text --reporter html --reporter lcovonly npm run test-node",
"test": "npm run test-node && npm run test-headless",
"prettier:check": "prettier --check '**/*.{js,css,md}'",
"prettier:write": "prettier --write '**/*.{js,css,md}'",
"preversion": "./scripts/preversion.sh",
"version": "./scripts/version.sh",
"postversion": "./scripts/postversion.sh",
"prepare": "husky",
"types:build": "tsgo -p tsconfig.types.json",
"types:check": "tsgo -p tsconfig.types.json --noEmit",
"types:smoke": "tsgo -p test/typescript-consumer/tsconfig.json --noEmit"
},
"types": "./types/fake-timers-src.d.ts",
"lint-staged": {
"*.{js,css,md}": "prettier --check",
"*.js": "eslint"
},
"mochify": {
"reporter": "dot",
"timeout": 10000,
"bundle": "esbuild --bundle --sourcemap=inline --define:process.env.NODE_DEBUG=\"\"",
"bundle_stdin": "require",
"spec": "test/**/*-test.js"
},
"files": [
"src/",
"types/"
],
"devDependencies": {
"@mochify/cli": "^1.0.0",
"@mochify/driver-puppeteer": "^1.0.1",
"@mochify/driver-webdriver": "^1.0.0",
"@sinonjs/eslint-config": "^5.0.4",
"@sinonjs/referee-sinon": "12.0.0",
"@types/node": "^25.5.0",
"@typescript/native-preview": "^7.0.0-dev.20260401.1",
"esbuild": "^0.27.3",
"husky": "^9.1.7",
"jsdom": "28.1.0",
"lint-staged": "16.3.1",
"mocha": "11.7.5",
"nyc": "18.0.0",
"prettier": "3.8.1"
},
"main": "./src/fake-timers-src.js",
"dependencies": {
"@sinonjs/commons": "^3.0.1"
},
"nyc": {
"branches": 85,
"lines": 92,
"functions": 92,
"statements": 92,
"exclude": [
"**/*-test.js",
"coverage/**",
"types/**",
"fake-timers.js"
]
},
"browser": {
"node:timers": false,
"node:timers/promises": false,
"timers": false,
"timers/promises": false
}
}
File diff suppressed because it is too large Load Diff
+562
View File
@@ -0,0 +1,562 @@
export type TickMode = "nextAsync" | "manual" | "interval";
export type NextAsyncTickMode = {
mode: "nextAsync";
};
export type ManualTickMode = {
mode: "manual";
};
export type IntervalTickMode = {
mode: "interval";
delta?: number;
};
export type TimerTickMode = IntervalTickMode | NextAsyncTickMode | ManualTickMode;
export type TimeRemaining = () => number;
export type IdleDeadline = {
didTimeout: boolean;
timeRemaining: TimeRemaining;
};
export type RequestIdleCallbackCallback = (deadline: IdleDeadline) => any;
export type RequestIdleCallback = (callback: RequestIdleCallbackCallback, options?: {
timeout: number;
}) => number;
export type FakeMethod = "setTimeout" | "clearTimeout" | "setImmediate" | "clearImmediate" | "setInterval" | "clearInterval" | "Date" | "nextTick" | "hrtime" | "requestAnimationFrame" | "cancelAnimationFrame" | "requestIdleCallback" | "cancelIdleCallback" | "performance" | "queueMicrotask";
export type TimerId = number | NodeImmediate | Timer;
export type NextTick = (callback: VoidVarArgsFunc, ...args: any) => void;
export type SetImmediate = (callback: VoidVarArgsFunc, ...args: any) => NodeImmediate;
export type SetTimeout = (callback: VoidVarArgsFunc, delay?: number, ...args: any) => TimerId;
export type ClearTimeout = (id?: TimerId) => void;
export type SetInterval = (callback: VoidVarArgsFunc, delay?: number, ...args: any) => TimerId;
export type ClearInterval = (id?: TimerId) => void;
export type QueueMicrotask = (callback: VoidVarArgsFunc) => void;
export type VoidVarArgsFunc = (...args: any) => void;
export type PerformanceNow = () => number;
export type Performance = {
now: PerformanceNow;
mark?: (name: string) => void;
measure?: (name: string, start?: string, end?: string) => void;
timeOrigin?: number;
};
export type AnimationFrameCallback = (time: number) => void;
export type RequestAnimationFrame = (callback: AnimationFrameCallback) => TimerId;
export type CancelAnimationFrame = (id: TimerId) => void;
export type CancelIdleCallback = (id: TimerId) => void;
export type ClearImmediate = (id: NodeImmediate) => void;
export type CountTimers = () => number;
export type RunMicrotasks = () => void;
export type Tick = (tickValue: string | number) => number;
export type TickAsync = (tickValue: string | number) => Promise<number>;
export type Next = () => number;
export type NextAsync = () => Promise<number>;
export type RunAll = () => number;
export type RunToFrame = () => number;
export type RunAllAsync = () => Promise<number>;
export type RunToLast = () => number;
export type RunToLastAsync = () => Promise<number>;
export type Reset = () => void;
export type SetSystemTime = (systemTime?: number | Date) => void;
export type Jump = (ms: number) => number;
export type Uninstall = () => void;
export type SetTickMode = (mode: TimerTickMode) => void;
export type Hrtime = (prevTime?: number[]) => number[];
export type WithGlobal = (globalObject: any) => FakeTimers;
export type Timers = {
setTimeout: SetTimeout;
clearTimeout: ClearTimeout;
setInterval: SetInterval;
clearInterval: ClearInterval;
Date: Date;
Intl?: typeof Intl;
setImmediate?: SetImmediate;
clearImmediate?: ClearImmediate;
hrtime?: Hrtime;
nextTick?: NextTick;
performance?: Performance;
requestAnimationFrame?: RequestAnimationFrame;
queueMicrotask?: QueueMicrotask;
cancelAnimationFrame?: CancelAnimationFrame;
requestIdleCallback?: RequestIdleCallback;
cancelIdleCallback?: CancelIdleCallback;
};
export type ClockState = {
tickFrom: number;
tickTo: number;
previous?: number;
oldNow?: number | null;
timer?: Timer;
firstException?: any;
nanosTotal?: number;
msFloat?: number;
ms?: number;
};
export type TimerInitialProps = {
func: VoidVarArgsFunc;
args?: any[];
type?: 'Timeout' | 'Interval' | 'Immediate' | 'AnimationFrame' | 'IdleCallback';
delay?: number;
callAt?: number;
createdAt?: number;
immediate?: boolean;
id?: number;
error?: Error;
interval?: number;
animation?: boolean;
requestIdleCallback?: boolean;
order?: number;
heapIndex?: number;
};
export type CreateClockCallback = (start?: number | Date, loopLimit?: number) => Clock;
export type InstallCallback = (config?: Config) => Clock;
export type FakeTimers = {
timers: Timers;
createClock: CreateClockCallback;
install: InstallCallback;
withGlobal: WithGlobal;
};
export type Clock = {
now: number;
Date: typeof Date & {
clock?: Clock;
};
loopLimit: number;
requestIdleCallback: RequestIdleCallback;
cancelIdleCallback: CancelIdleCallback;
setTimeout: SetTimeout;
clearTimeout: ClearTimeout;
nextTick: NextTick;
queueMicrotask: QueueMicrotask;
setInterval: SetInterval;
clearInterval: ClearInterval;
setImmediate: SetImmediate;
clearImmediate: ClearImmediate;
countTimers: CountTimers;
requestAnimationFrame: RequestAnimationFrame;
cancelAnimationFrame: CancelAnimationFrame;
runMicrotasks: RunMicrotasks;
tick: Tick;
tickAsync: TickAsync;
next: Next;
nextAsync: NextAsync;
runAll: RunAll;
runToFrame: RunToFrame;
runAllAsync: RunAllAsync;
runToLast: RunToLast;
runToLastAsync: RunToLastAsync;
reset: Reset;
setSystemTime: SetSystemTime;
jump: Jump;
performance: Performance;
hrtime: Hrtime;
uninstall: Uninstall;
methods: string[];
shouldClearNativeTimers?: boolean;
timersModuleMethods: {
methodName: string;
original: any;
}[] | undefined;
timersPromisesModuleMethods: {
methodName: string;
original: any;
}[] | undefined;
abortListenerMap: Map<VoidVarArgsFunc, AbortSignal>;
setTickMode: SetTickMode;
timers?: Map<number, Timer>;
timerHeap?: any;
duringTick?: boolean;
isNearInfiniteLimit: boolean;
attachedInterval?: any;
tickMode?: any;
jobs?: Timer[];
Intl?: any;
};
export type Config = {
now?: number | Date;
toFake?: FakeMethod[];
toNotFake?: FakeMethod[];
loopLimit?: number;
shouldAdvanceTime?: boolean;
advanceTimeDelta?: number;
shouldClearNativeTimers?: boolean;
ignoreMissingTimers?: boolean;
target?: object;
};
export type Timer = TimerInitialProps;
export type NodeImmediateHasRef = () => boolean;
export type NodeImmediateRef = () => NodeImmediate;
export type NodeImmediateUnref = () => NodeImmediate;
export type NodeImmediate = {
hasRef: NodeImmediateHasRef;
ref: NodeImmediateRef;
unref: NodeImmediateUnref;
};
/**
* @typedef {"nextAsync" | "manual" | "interval"} TickMode
*/
/**
* @typedef {object} NextAsyncTickMode
* @property {"nextAsync"} mode - runs timers one macrotask at a time
*/
/**
* @typedef {object} ManualTickMode
* @property {"manual"} mode - advances only when the caller explicitly ticks
*/
/**
* @typedef {object} IntervalTickMode
* @property {"interval"} mode - advances automatically on a native interval
* @property {number} [delta] - interval duration in milliseconds
*/
/**
* @typedef {IntervalTickMode | NextAsyncTickMode | ManualTickMode} TimerTickMode
*/
/**
* @callback TimeRemaining
* @returns {number}
*/
/**
* @typedef {object} IdleDeadline
* @property {boolean} didTimeout - whether or not the callback was called before reaching the optional timeout
* @property {TimeRemaining} timeRemaining - a floating-point value providing an estimate of the number of milliseconds remaining in the current idle period
*/
/**
* @callback RequestIdleCallbackCallback
* @param {IdleDeadline} deadline
*/
/**
* Queues a function to be called during a browser's idle periods
* @callback RequestIdleCallback
* @param {RequestIdleCallbackCallback} callback
* @param {{timeout: number}} [options] - an options object
* @returns {number} the id
*/
/**
* @typedef {"setTimeout" | "clearTimeout" | "setImmediate" | "clearImmediate" | "setInterval" | "clearInterval" | "Date" | "nextTick" | "hrtime" | "requestAnimationFrame" | "cancelAnimationFrame" | "requestIdleCallback" | "cancelIdleCallback" | "performance" | "queueMicrotask"} FakeMethod
*/
/**
* @typedef {number | NodeImmediate | Timer} TimerId
*/
/**
* @callback NextTick
* @param {VoidVarArgsFunc} callback - the callback to run
* @param {...*} args - optional arguments to call the callback with
* @returns {void}
*/
/**
* @callback SetImmediate
* @param {VoidVarArgsFunc} callback - the callback to run
* @param {...*} args - optional arguments to call the callback with
* @returns {NodeImmediate}
*/
/**
* @callback SetTimeout
* @param {VoidVarArgsFunc} callback - the callback to run
* @param {number} [delay] - optional delay in milliseconds
* @param {...*} args - optional arguments to call the callback with
* @returns {TimerId} - the timeout identifier
*/
/**
* @callback ClearTimeout
* @param {TimerId} [id] - the timeout identifier to clear
* @returns {void}
*/
/**
* @callback SetInterval
* @param {VoidVarArgsFunc} callback - the callback to run
* @param {number} [delay] - optional delay in milliseconds
* @param {...*} args - optional arguments to call the callback with
* @returns {TimerId} - the interval identifier
*/
/**
* @callback ClearInterval
* @param {TimerId} [id] - the interval identifier to clear
* @returns {void}
*/
/**
* @callback QueueMicrotask
* @param {VoidVarArgsFunc} callback - the callback to run
* @returns {void}
*/
/**
* @callback VoidVarArgsFunc
* @param {...*} args - optional arguments to call the callback with
* @returns {void}
*/
/**
* @callback PerformanceNow
* @returns {number}
*/
/**
* @typedef Performance
* @property {PerformanceNow} now - returns the current high-resolution time
* @property {(name: string) => void} [mark] - adds a mark
* @property {(name: string, start?: string, end?: string) => void} [measure] - adds a measure
* @property {number} [timeOrigin] - the time origin
*/
/**
* @callback AnimationFrameCallback
* @param {number} time - the current time
* @returns {void}
*/
/**
* @callback RequestAnimationFrame
* @param {AnimationFrameCallback} callback - schedules a frame callback
* @returns {TimerId} - the request id
*/
/**
* @callback CancelAnimationFrame
* @param {TimerId} id - cancels a frame callback
* @returns {void}
*/
/**
* @callback CancelIdleCallback
* @param {TimerId} id - cancels a scheduled idle callback
* @returns {void}
*/
/**
* @callback ClearImmediate
* @param {NodeImmediate} id - faked `clearImmediate`
* @returns {void}
*/
/**
* @callback CountTimers
* @returns {number}
*/
/**
* @callback RunMicrotasks
* @returns {void}
*/
/**
* @callback Tick
* @param {string | number} tickValue - advancement in milliseconds or a string
* @returns {number}
*/
/**
* @callback TickAsync
* @param {string | number} tickValue - advancement in milliseconds or a string
* @returns {Promise<number>}
*/
/**
* @callback Next
* @returns {number}
*/
/**
* @callback NextAsync
* @returns {Promise<number>}
*/
/**
* @callback RunAll
* @returns {number}
*/
/**
* @callback RunToFrame
* @returns {number}
*/
/**
* @callback RunAllAsync
* @returns {Promise<number>}
*/
/**
* @callback RunToLast
* @returns {number}
*/
/**
* @callback RunToLastAsync
* @returns {Promise<number>}
*/
/**
* @callback Reset
* @returns {void}
*/
/**
* @callback SetSystemTime
* @param {number | Date} [systemTime] - the time to set
* @returns {void}
*/
/**
* @callback Jump
* @param {number} ms - advancement in milliseconds
* @returns {number}
*/
/**
* @callback Uninstall
* @returns {void}
*/
/**
* @callback SetTickMode
* @param {TimerTickMode} mode - the new tick mode
* @returns {void}
*/
/**
* @callback Hrtime
* @param {number[]} [prevTime] - previous high-resolution time
* @returns {number[]}
*/
/**
* @callback WithGlobal
* @param {*} globalObject - the global object to mock
* @returns {FakeTimers}
*/
/**
* @typedef {object} Timers
* @property {SetTimeout} setTimeout - native `setTimeout`
* @property {ClearTimeout} clearTimeout - native `clearTimeout`
* @property {SetInterval} setInterval - native `setInterval`
* @property {ClearInterval} clearInterval - native `clearInterval`
* @property {Date} Date - native `Date`
* @property {typeof Intl} [Intl] - native `Intl`
* @property {SetImmediate} [setImmediate] - native `setImmediate`, if available
* @property {ClearImmediate} [clearImmediate] - native `clearImmediate`, if available
* @property {Hrtime} [hrtime] - native `process.hrtime`, if available
* @property {NextTick} [nextTick] - native `process.nextTick`, if available
* @property {Performance} [performance] - native `performance`, if available
* @property {RequestAnimationFrame} [requestAnimationFrame] - native `requestAnimationFrame`, if available
* @property {QueueMicrotask} [queueMicrotask] - whether `queueMicrotask` exists
* @property {CancelAnimationFrame} [cancelAnimationFrame] - native `cancelAnimationFrame`, if available
* @property {RequestIdleCallback} [requestIdleCallback] - native `requestIdleCallback`, if available
* @property {CancelIdleCallback} [cancelIdleCallback] - native `cancelIdleCallback`, if available
*/
/**
* @typedef {object} ClockState
* @property {number} tickFrom - lower bound of the current tick range
* @property {number} tickTo - upper bound of the current tick range
* @property {number} [previous] - previous timer time used during ticking
* @property {number | null} [oldNow] - previous value of `now`
* @property {Timer} [timer] - timer currently being processed
* @property {any} [firstException] - first exception raised while processing timers
* @property {number} [nanosTotal] - accumulated nanoseconds from fractional ticks
* @property {number} [msFloat] - accumulated fractional milliseconds
* @property {number} [ms] - accumulated whole milliseconds
*/
/**
* @typedef {object} TimerInitialProps
* @property {VoidVarArgsFunc} func - callback or string to execute
* @property {*[]} [args] - arguments passed to the callback
* @property {'Timeout' | 'Interval' | 'Immediate' | 'AnimationFrame' | 'IdleCallback'} [type] - timer kind
* @property {number} [delay] - requested delay in milliseconds
* @property {number} [callAt] - scheduled execution time
* @property {number} [createdAt] - time at which the timer was created
* @property {boolean} [immediate] - whether this timer should run before non-immediate timers at the same time
* @property {number} [id] - unique timer identifier
* @property {Error} [error] - captured stack for loop diagnostics
* @property {number} [interval] - interval for repeated timers
* @property {boolean} [animation] - whether this is an animation frame timer
* @property {boolean} [requestIdleCallback] - whether this is an idle callback timer
* @property {number} [order] - execution order for timers at the same time
* @property {number} [heapIndex] - index in the timer heap
*/
/**
* @callback CreateClockCallback
* @param {number|Date} [start] initial mocked time, as milliseconds since epoch or a Date
* @param {number} [loopLimit] maximum number of timers run before aborting with an infinite-loop error
* @returns {Clock}
*/
/**
* @callback InstallCallback
* @param {Config} [config] Optional config
* @returns {Clock}
*/
/**
* @typedef {object} FakeTimers
* @property {Timers} timers - the native timer APIs saved for later restoration
* @property {CreateClockCallback} createClock - creates a new fake clock
* @property {InstallCallback} install - installs the fake timers onto the default global object
* @property {WithGlobal} withGlobal - creates a fake-timers instance for a provided global object
*/
/**
* @typedef {object} Clock
* @property {number} now - current mocked time in milliseconds
* @property {typeof Date & {clock?: Clock}} Date - fake Date constructor bound to this clock
* @property {number} loopLimit - maximum number of timers before assuming an infinite loop
* @property {RequestIdleCallback} requestIdleCallback - schedules an idle callback
* @property {CancelIdleCallback} cancelIdleCallback - cancels a scheduled idle callback
* @property {SetTimeout} setTimeout - faked `setTimeout`
* @property {ClearTimeout} clearTimeout - faked `clearTimeout`
* @property {NextTick} nextTick - faked `process.nextTick`
* @property {QueueMicrotask} queueMicrotask - faked `queueMicrotask`
* @property {SetInterval} setInterval - faked `setInterval`
* @property {ClearInterval} clearInterval - faked `clearInterval`
* @property {SetImmediate} setImmediate - faked `setImmediate`
* @property {ClearImmediate} clearImmediate - faked `clearImmediate`
* @property {CountTimers} countTimers - counts scheduled timers
* @property {RequestAnimationFrame} requestAnimationFrame - schedules a frame callback
* @property {CancelAnimationFrame} cancelAnimationFrame - cancels a frame callback
* @property {RunMicrotasks} runMicrotasks - drains microtasks
* @property {Tick} tick - advances fake time synchronously
* @property {TickAsync} tickAsync - advances fake time asynchronously
* @property {Next} next - runs the next scheduled timer
* @property {NextAsync} nextAsync - runs the next scheduled timer asynchronously
* @property {RunAll} runAll - runs all scheduled timers
* @property {RunToFrame} runToFrame - runs timers up to the next animation frame
* @property {RunAllAsync} runAllAsync - runs all scheduled timers asynchronously
* @property {RunToLast} runToLast - runs timers up to the last scheduled timer
* @property {RunToLastAsync} runToLastAsync - runs timers up to the last scheduled timer asynchronously
* @property {Reset} reset - clears all timers and resets the clock
* @property {SetSystemTime} setSystemTime - sets the clock to a specific wall-clock time
* @property {Jump} jump - advances time and returns the new `now`
* @property {Performance} performance - fake performance object
* @property {Hrtime} hrtime - faked `process.hrtime`
* @property {Uninstall} uninstall - restores native timers
* @property {string[]} methods - names of faked methods
* @property {boolean} [shouldClearNativeTimers] - inherited from config
* @property {{methodName:string, original:any}[] | undefined} timersModuleMethods - saved Node timers module methods
* @property {{methodName:string, original:any}[] | undefined} timersPromisesModuleMethods - saved Node timers/promises methods
* @property {Map<VoidVarArgsFunc, AbortSignal>} abortListenerMap - active abort listeners
* @property {SetTickMode} setTickMode - switches the auto-tick mode
* @property {Map<number, Timer>} [timers] - internal timer storage
* @property {any} [timerHeap] - internal timer heap
* @property {boolean} [duringTick] - internal flag
* @property {boolean} isNearInfiniteLimit - internal flag indicating the loop limit is nearly reached
* @property {any} [attachedInterval] - internal flag
* @property {any} [tickMode] - internal flag
* @property {Timer[]} [jobs] - internal flag
* @property {any} [Intl] - fake Intl object
*/
/**
* Configuration object for the `install` method.
* @typedef {object} Config
* @property {number|Date} [now] initial mocked time, as milliseconds since epoch or a Date
* @property {FakeMethod[]} [toFake] method names that should be faked
* @property {FakeMethod[]} [toNotFake] method names that should remain native
* @property {number} [loopLimit] maximum number of timers run before aborting with an infinite-loop error
* @property {boolean} [shouldAdvanceTime] automatically increments mocked time while the clock is installed
* @property {number} [advanceTimeDelta] interval in milliseconds used when `shouldAdvanceTime` is enabled
* @property {boolean} [shouldClearNativeTimers] forwards clear calls to native methods when the timer is not fake
* @property {boolean} [ignoreMissingTimers] suppresses errors when a requested timer is missing from the global object
* @property {object} [target] global object to install onto
*/
/**
* The internal structure to describe a scheduled fake timer
* @typedef {TimerInitialProps} Timer
* @property {*[]} args - arguments passed to the callback
* @property {number} callAt - scheduled execution time
* @property {number} createdAt - time at which the timer was created
* @property {number} id - unique timer identifier
* @property {'Timeout' | 'Interval' | 'Immediate' | 'AnimationFrame' | 'IdleCallback'} type - timer kind
*/
/**
* @callback NodeImmediateHasRef
* @returns {boolean}
*/
/**
* @callback NodeImmediateRef
* @returns {NodeImmediate}
*/
/**
* @callback NodeImmediateUnref
* @returns {NodeImmediate}
*/
/**
* A Node timer
* @typedef {object} NodeImmediate
* @property {NodeImmediateHasRef} hasRef - reports whether the timer keeps the event loop alive
* @property {NodeImmediateRef} ref - marks the timer as referenced
* @property {NodeImmediateUnref} unref - marks the timer as unreferenced
*/
/**
* Mocks available features in the specified global namespace.
* @param {*} _global Namespace to mock (e.g. `window`)
* @returns {FakeTimers}
*/
declare function withGlobal(_global: any): FakeTimers;
export declare var timers: Timers;
export declare var createClock: CreateClockCallback;
export declare var install: InstallCallback;
export declare var withGlobal: typeof withGlobal;