diff --git a/README.md b/README.md
index 1882a36f2..1babe9962 100644
--- a/README.md
+++ b/README.md
@@ -22,7 +22,6 @@ Next generation testing framework powered by Vite.
中文文档
-
@@ -49,7 +48,6 @@ Next generation testing framework powered by Vite.
> Vitest 1.0 requires Vite >=v5.0.0 and Node >=v18.0.0
-
```ts
import { assert, describe, expect, it } from 'vitest'
diff --git a/docs/advanced/runner.md b/docs/advanced/runner.md
index c841ee035..da8bf1a99 100644
--- a/docs/advanced/runner.md
+++ b/docs/advanced/runner.md
@@ -11,69 +11,69 @@ export interface VitestRunner {
/**
* First thing that's getting called before actually collecting and running tests.
*/
- onBeforeCollect?(paths: string[]): unknown
+ onBeforeCollect?: (paths: string[]) => unknown
/**
* Called after collecting tests and before "onBeforeRun".
*/
- onCollected?(files: File[]): unknown
+ onCollected?: (files: File[]) => unknown
/**
* Called when test runner should cancel next test runs.
* Runner should listen for this method and mark tests and suites as skipped in
* "onBeforeRunSuite" and "onBeforeRunTask" when called.
*/
- onCancel?(reason: CancelReason): unknown
+ onCancel?: (reason: CancelReason) => unknown
/**
* Called before running a single test. Doesn't have "result" yet.
*/
- onBeforeRunTask?(test: TaskPopulated): unknown
+ onBeforeRunTask?: (test: TaskPopulated) => unknown
/**
* Called before actually running the test function. Already has "result" with "state" and "startTime".
*/
- onBeforeTryTask?(test: TaskPopulated, options: { retry: number; repeats: number }): unknown
+ onBeforeTryTask?: (test: TaskPopulated, options: { retry: number; repeats: number }) => unknown
/**
* Called after result and state are set.
*/
- onAfterRunTask?(test: TaskPopulated): unknown
+ onAfterRunTask?: (test: TaskPopulated) => unknown
/**
* Called right after running the test function. Doesn't have new state yet. Will not be called, if the test function throws.
*/
- onAfterTryTask?(test: TaskPopulated, options: { retry: number; repeats: number }): unknown
+ onAfterTryTask?: (test: TaskPopulated, options: { retry: number; repeats: number }) => unknown
/**
* Called before running a single suite. Doesn't have "result" yet.
*/
- onBeforeRunSuite?(suite: Suite): unknown
+ onBeforeRunSuite?: (suite: Suite) => unknown
/**
* Called after running a single suite. Has state and result.
*/
- onAfterRunSuite?(suite: Suite): unknown
+ onAfterRunSuite?: (suite: Suite) => unknown
/**
* If defined, will be called instead of usual Vitest suite partition and handling.
* "before" and "after" hooks will not be ignored.
*/
- runSuite?(suite: Suite): Promise
+ runSuite?: (suite: Suite) => Promise
/**
* If defined, will be called instead of usual Vitest handling. Useful, if you have your custom test function.
* "before" and "after" hooks will not be ignored.
*/
- runTask?(test: TaskPopulated): Promise
+ runTask?: (test: TaskPopulated) => Promise
/**
* Called, when a task is updated. The same as "onTaskUpdate" in a reporter, but this is running in the same thread as tests.
*/
- onTaskUpdate?(task: [string, TaskResult | undefined][]): Promise
+ onTaskUpdate?: (task: [string, TaskResult | undefined][]) => Promise
/**
* Called before running all tests in collected paths.
*/
- onBeforeRunFiles?(files: File[]): unknown
+ onBeforeRunFiles?: (files: File[]) => unknown
/**
* Called right after running all tests in collected paths.
*/
- onAfterRunFiles?(files: File[]): unknown
+ onAfterRunFiles?: (files: File[]) => unknown
/**
* Called when new context for a test is defined. Useful, if you want to add custom properties to the context.
* If you only want to define custom context with a runner, consider using "beforeAll" in "setupFiles" instead.
@@ -82,11 +82,11 @@ export interface VitestRunner {
*
* @see https://vitest.dev/advanced/runner.html#your-task-function
*/
- extendTaskContext?(context: TaskContext): TaskContext
+ extendTaskContext?: (context: TaskContext) => TaskContext
/**
* Called, when certain files are imported. Can be called in two situations: when collecting tests and when importing setup files.
*/
- importFile(filepath: string, source: VitestRunnerImportSource): unknown
+ importFile: (filepath: string, source: VitestRunnerImportSource) => unknown
/**
* Publicly available configuration.
*/
diff --git a/docs/api/expect.md b/docs/api/expect.md
index 242251f48..5bf3ac2f4 100644
--- a/docs/api/expect.md
+++ b/docs/api/expect.md
@@ -1389,7 +1389,7 @@ If you are using TypeScript, since Vitest 0.31.0 you can extend default `Asserti
```ts
interface CustomMatchers {
- toBeFoo(): R
+ toBeFoo: () => R
}
declare module 'vitest' {
@@ -1456,4 +1456,4 @@ expect.addEqualityTesters([areAnagramsEqual])
test('custom equality tester', () => {
expect(new AnagramComparator('listen')).toEqual(new AnagramComparator('silent'))
})
-```
\ No newline at end of file
+```
diff --git a/docs/api/index.md b/docs/api/index.md
index f24573091..7df39b390 100644
--- a/docs/api/index.md
+++ b/docs/api/index.md
@@ -209,7 +209,6 @@ test.todo.concurrent(/* ... */) // or test.concurrent.todo(/* ... */)
When running concurrent tests, Snapshots and Assertions must use `expect` from the local [Test Context](/guide/test-context.md) to ensure the right test is detected.
-
```ts
test.concurrent('test 1', async ({ expect }) => {
expect(foo).toMatchSnapshot()
diff --git a/docs/config/index.md b/docs/config/index.md
index e2690c3d4..cf0c627dc 100644
--- a/docs/config/index.md
+++ b/docs/config/index.md
@@ -702,7 +702,6 @@ Minimum number of threads. You can also use `VITEST_MIN_THREADS` environment var
Run all tests with the same environment inside a single worker thread. This will disable built-in module isolation (your source code or [inlined](#deps-inline) code will still be reevaluated for each test), but can improve test performance.
-
:::warning
Even though this option will force tests to run one after another, this option is different from Jest's `--runInBand`. Vitest uses workers not only for running tests in parallel, but also to provide isolation. By disabling this option, your tests will run sequentially, but in the same global context, so you must provide isolation yourself.
@@ -782,7 +781,6 @@ Isolate environment for each test file.
Run all tests with the same environment inside a single child process. This will disable built-in module isolation (your source code or [inlined](#deps-inline) code will still be reevaluated for each test), but can improve test performance.
-
:::warning
Even though this option will force tests to run one after another, this option is different from Jest's `--runInBand`. Vitest uses child processes not only for running tests in parallel, but also to provide isolation. By disabling this option, your tests will run sequentially, but in the same global context, so you must provide isolation yourself.
@@ -881,7 +879,6 @@ Pass additional arguments to `node` process in the VM context. See [Command-line
Be careful when using, it as some options may crash worker, e.g. --prof, --title. See https://github.com/nodejs/node/issues/41103.
:::
-
#### poolOptions.vmForks
Options for `vmForks` pool.
@@ -1063,7 +1060,6 @@ declare module 'vitest' {
```
:::
-
### watchExclude
- **Type:** `string[]`
@@ -1557,10 +1553,10 @@ Path to a provider that will be used when running browser tests. Vitest provides
```ts
export interface BrowserProvider {
name: string
- getSupportedBrowsers(): readonly string[]
- initialize(ctx: Vitest, options: { browser: string; options?: BrowserProviderOptions }): Awaitable
- openPage(url: string): Awaitable
- close(): Awaitable
+ getSupportedBrowsers: () => readonly string[]
+ initialize: (ctx: Vitest, options: { browser: string; options?: BrowserProviderOptions }) => Awaitable
+ openPage: (url: string) => Awaitable
+ close: () => Awaitable
}
```
diff --git a/docs/guide/extending-matchers.md b/docs/guide/extending-matchers.md
index 8e9974339..82b542ef1 100644
--- a/docs/guide/extending-matchers.md
+++ b/docs/guide/extending-matchers.md
@@ -29,7 +29,7 @@ If you are using TypeScript, since Vitest 0.31.0 you can extend default `Asserti
import type { Assertion, AsymmetricMatchersContaining } from 'vitest'
interface CustomMatchers {
- toBeFoo(): R
+ toBeFoo: () => R
}
declare module 'vitest' {
diff --git a/docs/guide/filtering.md b/docs/guide/filtering.md
index d3a5e82ff..462d3cf95 100644
--- a/docs/guide/filtering.md
+++ b/docs/guide/filtering.md
@@ -22,7 +22,7 @@ basic-foo.test.ts
basic/foo.test.ts
```
-You can also use the `-t, --testNamePattern ` option to filter tests by full name. This can be helpful when you want to filter by the name defined within a file rather than the filename itself.
+You can also use the `-t, --testNamePattern ` option to filter tests by full name. This can be helpful when you want to filter by the name defined within a file rather than the filename itself.
## Specifying a Timeout
diff --git a/docs/guide/migration.md b/docs/guide/migration.md
index c13233e52..2e82cc8b8 100644
--- a/docs/guide/migration.md
+++ b/docs/guide/migration.md
@@ -19,7 +19,6 @@ All `@vitest/*` sub packages require Vitest version 1.0.
Quotes in snapshots are no longer escaped, and all snapshots use backtick quotes (`) even if the string is just a single line.
-
1. Quotes are no longer escaped:
```diff
@@ -44,7 +43,6 @@ There were also [changes](https://github.com/vitest-dev/vitest/pull/4076) to `@v
- `client.setTest` was renamed to `client.startCurrentRun`
- `client.resetCurrent` was renamed to `client.finishCurrentRun`
-
### Pools are Standardized [#4172](https://github.com/vitest-dev/vitest/pull/4172)
We removed a lot of configuration options to make it easier to configure the runner to your needs. Please, have a look at migration examples if you rely on `--threads` or other related flags.
@@ -145,7 +143,6 @@ A few types were removed in favor of Jest-style "Mock" naming.
`SpyInstance` is deprecated in favor of `MockInstance` and will be removed in the next major release.
:::
-
### Timer mocks [#3925](https://github.com/vitest-dev/vitest/pull/3925)
`vi.useFakeTimers()` no longer automatically mocks [`process.nextTick`](https://nodejs.org/api/process.html#processnexttickcallback-args).
diff --git a/docs/guide/mocking.md b/docs/guide/mocking.md
index 87c88e160..e40b9b108 100644
--- a/docs/guide/mocking.md
+++ b/docs/guide/mocking.md
@@ -362,7 +362,6 @@ Because Vitest runs in Node, mocking network requests is tricky; web APIs are no
Mock Service Worker (MSW) works by intercepting the requests your tests make, allowing you to use it without changing any of your application code. In-browser, this uses the [Service Worker API](https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API). In Node.js, and for Vitest, it uses the [`@mswjs/interceptors`](https://github.com/mswjs/interceptors) library. To learn more about MSW, read their [introduction](https://mswjs.io/docs/)
-
### Configuration
You can use it like below in your [setup file](/config/#setupfiles)
diff --git a/docs/guide/reporters.md b/docs/guide/reporters.md
index 933602a80..699bec9d6 100644
--- a/docs/guide/reporters.md
+++ b/docs/guide/reporters.md
@@ -426,7 +426,6 @@ not ok 1 - __tests__/test-file-1.test.ts > first test file > 2 + 2 should equal
ok 2 - __tests__/test-file-1.test.ts > first test file > 4 - 2 should equal 2 # time=0.00ms
```
-
### Hanging Process Reporter
Displays a list of hanging processes, if any are preventing Vitest from exiting safely. The `hanging-process` reporter does not itself display test results, but can be used in conjunction with another reporter to monitor processes while tests run. Using this reporter can be resource-intensive, so should generally be reserved for debugging purposes in situations where Vitest consistently cannot exit the process.
@@ -453,8 +452,6 @@ to provide annotations for test failures. This reporter is automatically enabled
-
-
## Custom Reporters
You can use third-party custom reporters installed from NPM by specifying their package name in the reporters' option:
diff --git a/docs/guide/snapshot.md b/docs/guide/snapshot.md
index a91a10934..727ad8c99 100644
--- a/docs/guide/snapshot.md
+++ b/docs/guide/snapshot.md
@@ -159,7 +159,6 @@ export default {
} satisfies SnapshotSerializer
```
-
```ts
import { defineConfig } from 'vite'
diff --git a/docs/guide/ui.md b/docs/guide/ui.md
index 49c931190..6797091f9 100644
--- a/docs/guide/ui.md
+++ b/docs/guide/ui.md
@@ -18,7 +18,6 @@ vitest --ui
Then you can visit the Vitest UI at `http://localhost:51204/__vitest__/`
-
diff --git a/eslint.config.js b/eslint.config.js
index c23057a4b..0525bdb0b 100644
--- a/eslint.config.js
+++ b/eslint.config.js
@@ -24,8 +24,14 @@ export default antfu(
'node/prefer-global/process': 'off',
'no-empty-pattern': 'off',
'antfu/indent-binary-ops': 'off',
- 'style/member-delimiter-style': ['error', { multiline: { delimiter: 'none' }, singleline: { delimiter: 'semi' } }],
'unused-imports/no-unused-imports': 'error',
+ 'style/member-delimiter-style': [
+ 'error',
+ {
+ multiline: { delimiter: 'none' },
+ singleline: { delimiter: 'semi' },
+ },
+ ],
'ts/no-invalid-this': 'off',
@@ -42,6 +48,12 @@ export default antfu(
'import/no-named-as-default': 'off',
},
},
+ {
+ files: [`packages/*/*.{js,mjs,d.ts}`],
+ rules: {
+ 'antfu/no-import-dist': 'off',
+ },
+ },
{
files: [`packages/${GLOB_SRC}`],
rules: {
diff --git a/examples/image-snapshot/test/basic.test.ts b/examples/image-snapshot/test/basic.test.ts
index 537c8d1f7..54e35e293 100644
--- a/examples/image-snapshot/test/basic.test.ts
+++ b/examples/image-snapshot/test/basic.test.ts
@@ -4,7 +4,7 @@ import { toMatchImageSnapshot } from 'jest-image-snapshot'
declare module 'vitest' {
interface Assertion {
- toMatchImageSnapshot(): T
+ toMatchImageSnapshot: () => T
}
}
diff --git a/netlify.toml b/netlify.toml
index 7a1c0873a..fcf540413 100755
--- a/netlify.toml
+++ b/netlify.toml
@@ -1,19 +1,20 @@
-[build.environment]
- NODE_VERSION = "20"
- # don't need playwright for docs build
- PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD = "1"
-
[build]
- publish = "docs/.vitepress/dist"
- command = "pnpm docs:build"
- ignore = "git diff --quiet $COMMIT_REF $CACHED_COMMIT_REF -- docs/ package.json pnpm-lock.yaml"
+publish = "docs/.vitepress/dist"
+command = "pnpm docs:build"
+ignore = "git diff --quiet $COMMIT_REF $CACHED_COMMIT_REF -- docs/ package.json pnpm-lock.yaml"
+
+[build.environment]
+NODE_VERSION = "20"
+# don't need playwright for docs build
+PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD = "1"
[[redirects]]
- from = "/new"
- to = "https://stackblitz.com/fork/github/vitest-dev/vitest/tree/main/examples/basic?initialPath=__vitest__/"
- status = 302
+from = "/new"
+to = "https://stackblitz.com/fork/github/vitest-dev/vitest/tree/main/examples/basic?initialPath=__vitest__/"
+status = 302
[[headers]]
- for = "/manifest.webmanifest"
- [headers.values]
- Content-Type = "application/manifest+json"
+for = "/manifest.webmanifest"
+
+[headers.values]
+Content-Type = "application/manifest+json"
diff --git a/package.json b/package.json
index df4106b8e..baed07eca 100644
--- a/package.json
+++ b/package.json
@@ -38,7 +38,7 @@
"test:browser:playwright": "pnpm -C test/browser run test:playwright"
},
"devDependencies": {
- "@antfu/eslint-config": "^1.2.1",
+ "@antfu/eslint-config": "^2.6.4",
"@antfu/ni": "^0.21.12",
"@rollup/plugin-commonjs": "^25.0.7",
"@rollup/plugin-json": "^6.0.1",
diff --git a/packages/browser/package.json b/packages/browser/package.json
index 478a9c545..efeba6c3c 100644
--- a/packages/browser/package.json
+++ b/packages/browser/package.json
@@ -55,13 +55,13 @@
"webdriverio": "*"
},
"peerDependenciesMeta": {
- "webdriverio": {
+ "playwright": {
"optional": true
},
"safaridriver": {
"optional": true
},
- "playwright": {
+ "webdriverio": {
"optional": true
}
},
diff --git a/packages/browser/src/client/runner.ts b/packages/browser/src/client/runner.ts
index 64259d1e8..63a9be827 100644
--- a/packages/browser/src/client/runner.ts
+++ b/packages/browser/src/client/runner.ts
@@ -1,4 +1,4 @@
-import type { File, TaskResultPack, Test, VitestRunner } from '@vitest/runner'
+import type { File, Task, TaskResultPack, VitestRunner } from '@vitest/runner'
import type { ResolvedConfig } from 'vitest'
import type { VitestExecutor } from 'vitest/execute'
import { rpc } from './rpc'
@@ -16,10 +16,10 @@ interface CoverageHandler {
}
export function createBrowserRunner(
- VitestRunner: { new(config: ResolvedConfig): VitestRunner },
+ runnerClass: { new(config: ResolvedConfig): VitestRunner },
coverageModule: CoverageHandler | null,
): { new(options: BrowserRunnerOptions): VitestRunner } {
- return class BrowserTestRunner extends VitestRunner {
+ return class BrowserTestRunner extends runnerClass implements VitestRunner {
public config: ResolvedConfig
hashMap = browserHashMap
@@ -28,7 +28,7 @@ export function createBrowserRunner(
this.config = options.config
}
- async onAfterRunTask(task: Test) {
+ onAfterRunTask = async (task: Task) => {
await super.onAfterRunTask?.(task)
if (this.config.bail && task.result?.state === 'fail') {
@@ -42,7 +42,7 @@ export function createBrowserRunner(
}
}
- async onAfterRunFiles(files: File[]) {
+ onAfterRunFiles = async (files: File[]) => {
await super.onAfterRunFiles?.(files)
const coverage = await coverageModule?.takeCoverage?.()
@@ -55,15 +55,15 @@ export function createBrowserRunner(
}
}
- onCollected(files: File[]): unknown {
+ onCollected = (files: File[]): unknown => {
return rpc().onCollected(files)
}
- onTaskUpdate(task: TaskResultPack[]): Promise {
+ onTaskUpdate = (task: TaskResultPack[]): Promise => {
return rpc().onTaskUpdate(task)
}
- async importFile(filepath: string) {
+ importFile = async (filepath: string) => {
let [test, hash] = this.hashMap.get(filepath) ?? [false, '']
if (hash === '') {
hash = Date.now().toString()
diff --git a/packages/browser/src/client/utils.ts b/packages/browser/src/client/utils.ts
index 69c7f0556..4880c2f2a 100644
--- a/packages/browser/src/client/utils.ts
+++ b/packages/browser/src/client/utils.ts
@@ -14,9 +14,9 @@ interface BrowserRunnerState {
runningFiles: string[]
moduleCache: WorkerGlobalState['moduleCache']
config: ResolvedConfig
- exportAll(): void
- wrapModule(module: any): any
- runTests(tests: string[]): Promise
+ exportAll: () => void
+ wrapModule: (module: any) => any
+ runTests: (tests: string[]) => Promise
}
export function getBrowserState(): BrowserRunnerState {
diff --git a/packages/coverage-istanbul/src/provider.ts b/packages/coverage-istanbul/src/provider.ts
index f869bb4b5..e80029f51 100644
--- a/packages/coverage-istanbul/src/provider.ts
+++ b/packages/coverage-istanbul/src/provider.ts
@@ -32,8 +32,8 @@ interface TestExclude {
excludeNodeModules?: boolean
relativePath?: boolean
}): {
- shouldInstrument(filePath: string): boolean
- glob(cwd: string): Promise
+ shouldInstrument: (filePath: string) => boolean
+ glob: (cwd: string) => Promise
}
}
diff --git a/packages/coverage-v8/src/provider.ts b/packages/coverage-v8/src/provider.ts
index e393ddc7a..18e225c43 100644
--- a/packages/coverage-v8/src/provider.ts
+++ b/packages/coverage-v8/src/provider.ts
@@ -35,8 +35,8 @@ interface TestExclude {
excludeNodeModules?: boolean
relativePath?: boolean
}): {
- shouldInstrument(filePath: string): boolean
- glob(cwd: string): Promise
+ shouldInstrument: (filePath: string) => boolean
+ glob: (cwd: string) => Promise
}
}
diff --git a/packages/expect/src/jest-asymmetric-matchers.ts b/packages/expect/src/jest-asymmetric-matchers.ts
index 424311d01..76759c3b8 100644
--- a/packages/expect/src/jest-asymmetric-matchers.ts
+++ b/packages/expect/src/jest-asymmetric-matchers.ts
@@ -6,10 +6,10 @@ import { diff, getCustomEqualityTesters, getMatcherUtils, stringify } from './je
import { equals, isA, iterableEquality, pluralize, subsetEquality } from './jest-utils'
export interface AsymmetricMatcherInterface {
- asymmetricMatch(other: unknown): boolean
- toString(): string
- getExpectedType?(): string
- toAsymmetricMatcher?(): string
+ asymmetricMatch: (other: unknown) => boolean
+ toString: () => string
+ getExpectedType?: () => string
+ toAsymmetricMatcher?: () => string
}
export abstract class AsymmetricMatcher<
diff --git a/packages/expect/src/types.ts b/packages/expect/src/types.ts
index 44df32476..7b1ed307f 100644
--- a/packages/expect/src/types.ts
+++ b/packages/expect/src/types.ts
@@ -91,72 +91,72 @@ export type MatchersObject = Record(actual: T, message?: string): Assertion
- unreachable(message?: string): never
- soft(actual: T, message?: string): Assertion
- extend(expects: MatchersObject): void
- addEqualityTesters(testers: Array): void
- assertions(expected: number): void
- hasAssertions(): void
- anything(): any
- any(constructor: unknown): any
- getState(): MatcherState
- setState(state: Partial): void
+ unreachable: (message?: string) => never
+ soft: (actual: T, message?: string) => Assertion
+ extend: (expects: MatchersObject) => void
+ addEqualityTesters: (testers: Array) => void
+ assertions: (expected: number) => void
+ hasAssertions: () => void
+ anything: () => any
+ any: (constructor: unknown) => any
+ getState: () => MatcherState
+ setState: (state: Partial) => void
not: AsymmetricMatchersContaining
}
export interface AsymmetricMatchersContaining {
- stringContaining(expected: string): any
- objectContaining(expected: T): any
- arrayContaining(expected: Array): any
- stringMatching(expected: string | RegExp): any
- closeTo(expected: number, precision?: number): any
+ stringContaining: (expected: string) => any
+ objectContaining: (expected: T) => any
+ arrayContaining: (expected: Array) => any
+ stringMatching: (expected: string | RegExp) => any
+ closeTo: (expected: number, precision?: number) => any
}
export interface JestAssertion extends jest.Matchers {
// Jest compact
- toEqual(expected: E): void
- toStrictEqual(expected: E): void
- toBe(expected: E): void
- toMatch(expected: string | RegExp): void
- toMatchObject(expected: E): void
- toContain(item: E): void
- toContainEqual(item: E): void
- toBeTruthy(): void
- toBeFalsy(): void
- toBeGreaterThan(num: number | bigint): void
- toBeGreaterThanOrEqual(num: number | bigint): void
- toBeLessThan(num: number | bigint): void
- toBeLessThanOrEqual(num: number | bigint): void
- toBeNaN(): void
- toBeUndefined(): void
- toBeNull(): void
- toBeDefined(): void
- toBeInstanceOf(expected: E): void
- toBeCalledTimes(times: number): void
- toHaveLength(length: number): void
- toHaveProperty(property: string | (string | number)[], value?: E): void
- toBeCloseTo(number: number, numDigits?: number): void
- toHaveBeenCalledTimes(times: number): void
- toHaveBeenCalled(): void
- toBeCalled(): void
- toHaveBeenCalledWith(...args: E): void
- toBeCalledWith(...args: E): void
- toHaveBeenNthCalledWith(n: number, ...args: E): void
- nthCalledWith(nthCall: number, ...args: E): void
- toHaveBeenLastCalledWith(...args: E): void
- lastCalledWith(...args: E): void
- toThrow(expected?: string | Constructable | RegExp | Error): void
- toThrowError(expected?: string | Constructable | RegExp | Error): void
- toReturn(): void
- toHaveReturned(): void
- toReturnTimes(times: number): void
- toHaveReturnedTimes(times: number): void
- toReturnWith(value: E): void
- toHaveReturnedWith(value: E): void
- toHaveLastReturnedWith(value: E): void
- lastReturnedWith(value: E): void
- toHaveNthReturnedWith(nthCall: number, value: E): void
- nthReturnedWith(nthCall: number, value: E): void
+ toEqual: (expected: E) => void
+ toStrictEqual: (expected: E) => void
+ toBe: (expected: E) => void
+ toMatch: (expected: string | RegExp) => void
+ toMatchObject: (expected: E) => void
+ toContain: (item: E) => void
+ toContainEqual: (item: E) => void
+ toBeTruthy: () => void
+ toBeFalsy: () => void
+ toBeGreaterThan: (num: number | bigint) => void
+ toBeGreaterThanOrEqual: (num: number | bigint) => void
+ toBeLessThan: (num: number | bigint) => void
+ toBeLessThanOrEqual: (num: number | bigint) => void
+ toBeNaN: () => void
+ toBeUndefined: () => void
+ toBeNull: () => void
+ toBeDefined: () => void
+ toBeInstanceOf: (expected: E) => void
+ toBeCalledTimes: (times: number) => void
+ toHaveLength: (length: number) => void
+ toHaveProperty: (property: string | (string | number)[], value?: E) => void
+ toBeCloseTo: (number: number, numDigits?: number) => void
+ toHaveBeenCalledTimes: (times: number) => void
+ toHaveBeenCalled: () => void
+ toBeCalled: () => void
+ toHaveBeenCalledWith: (...args: E) => void
+ toBeCalledWith: (...args: E) => void
+ toHaveBeenNthCalledWith: (n: number, ...args: E) => void
+ nthCalledWith: (nthCall: number, ...args: E) => void
+ toHaveBeenLastCalledWith: (...args: E) => void
+ lastCalledWith: (...args: E) => void
+ toThrow: (expected?: string | Constructable | RegExp | Error) => void
+ toThrowError: (expected?: string | Constructable | RegExp | Error) => void
+ toReturn: () => void
+ toHaveReturned: () => void
+ toReturnTimes: (times: number) => void
+ toHaveReturnedTimes: (times: number) => void
+ toReturnWith: (value: E) => void
+ toHaveReturnedWith: (value: E) => void
+ toHaveLastReturnedWith: (value: E) => void
+ lastReturnedWith: (value: E) => void
+ toHaveNthReturnedWith: (nthCall: number, value: E) => void
+ nthReturnedWith: (nthCall: number, value: E) => void
}
type VitestAssertion = {
@@ -176,9 +176,9 @@ type Promisify = {
}
export interface Assertion extends VitestAssertion, JestAssertion {
- toBeTypeOf(expected: 'bigint' | 'boolean' | 'function' | 'number' | 'object' | 'string' | 'symbol' | 'undefined'): void
- toHaveBeenCalledOnce(): void
- toSatisfy(matcher: (value: E) => boolean, message?: string): void
+ toBeTypeOf: (expected: 'bigint' | 'boolean' | 'function' | 'number' | 'object' | 'string' | 'symbol' | 'undefined') => void
+ toHaveBeenCalledOnce: () => void
+ toSatisfy: (matcher: (value: E) => boolean, message?: string) => void
resolves: Promisify>
rejects: Promisify>
diff --git a/packages/runner/src/types/runner.ts b/packages/runner/src/types/runner.ts
index 0f6fe71e6..6822c4903 100644
--- a/packages/runner/src/types/runner.ts
+++ b/packages/runner/src/types/runner.ts
@@ -1,5 +1,16 @@
import type { DiffOptions } from '@vitest/utils/diff'
-import type { Custom, ExtendedContext, File, SequenceHooks, SequenceSetupFiles, Suite, TaskContext, TaskPopulated, TaskResultPack, Test } from './tasks'
+import type {
+ Custom,
+ ExtendedContext,
+ File,
+ SequenceHooks,
+ SequenceSetupFiles,
+ Suite,
+ Task,
+ TaskContext,
+ TaskResultPack,
+ Test,
+} from './tasks'
export interface VitestRunnerConfig {
root: string
@@ -31,75 +42,81 @@ export interface VitestRunnerConstructor {
new(config: VitestRunnerConfig): VitestRunner
}
-export type CancelReason = 'keyboard-input' | 'test-failure' | string & Record
+export type CancelReason =
+ | 'keyboard-input'
+ | 'test-failure'
+ | string & Record
export interface VitestRunner {
/**
* First thing that's getting called before actually collecting and running tests.
*/
- onBeforeCollect?(paths: string[]): unknown
+ onBeforeCollect?: (paths: string[]) => unknown
/**
* Called after collecting tests and before "onBeforeRun".
*/
- onCollected?(files: File[]): unknown
+ onCollected?: (files: File[]) => unknown
/**
* Called when test runner should cancel next test runs.
* Runner should listen for this method and mark tests and suites as skipped in
* "onBeforeRunSuite" and "onBeforeRunTask" when called.
*/
- onCancel?(reason: CancelReason): unknown
+ onCancel?: (reason: CancelReason) => unknown
/**
* Called before running a single test. Doesn't have "result" yet.
*/
- onBeforeRunTask?(test: TaskPopulated): unknown
+ onBeforeRunTask?: (test: Task) => unknown
/**
* Called before actually running the test function. Already has "result" with "state" and "startTime".
*/
- onBeforeTryTask?(test: TaskPopulated, options: { retry: number; repeats: number }): unknown
+ onBeforeTryTask?: (test: Task, options: { retry: number; repeats: number }) => unknown
/**
* Called after result and state are set.
*/
- onAfterRunTask?(test: TaskPopulated): unknown
+ onAfterRunTask?: (test: Task) => unknown
/**
* Called right after running the test function. Doesn't have new state yet. Will not be called, if the test function throws.
*/
- onAfterTryTask?(test: TaskPopulated, options: { retry: number; repeats: number }): unknown
+ onAfterTryTask?: (
+ test: Task,
+ options: { retry: number; repeats: number }
+ ) => unknown
/**
* Called before running a single suite. Doesn't have "result" yet.
*/
- onBeforeRunSuite?(suite: Suite): unknown
+ onBeforeRunSuite?: (suite: Suite) => unknown
/**
* Called after running a single suite. Has state and result.
*/
- onAfterRunSuite?(suite: Suite): unknown
+ onAfterRunSuite?: (suite: Suite) => unknown
/**
* If defined, will be called instead of usual Vitest suite partition and handling.
* "before" and "after" hooks will not be ignored.
*/
- runSuite?(suite: Suite): Promise
+ runSuite?: (suite: Suite) => Promise
/**
* If defined, will be called instead of usual Vitest handling. Useful, if you have your custom test function.
* "before" and "after" hooks will not be ignored.
*/
- runTask?(test: TaskPopulated): Promise
+ runTask?: (test: Task) => Promise
/**
* Called, when a task is updated. The same as "onTaskUpdate" in a reporter, but this is running in the same thread as tests.
*/
- onTaskUpdate?(task: TaskResultPack[]): Promise
+ onTaskUpdate?: (task: TaskResultPack[]) => Promise
/**
* Called before running all tests in collected paths.
*/
- onBeforeRunFiles?(files: File[]): unknown
+ onBeforeRunFiles?: (files: File[]) => unknown
/**
* Called right after running all tests in collected paths.
*/
- onAfterRunFiles?(files: File[]): unknown
+ onAfterRunFiles?: (files: File[]) => unknown
/**
* Called when new context for a test is defined. Useful, if you want to add custom properties to the context.
* If you only want to define custom context, consider using "beforeAll" in "setupFiles" instead.
@@ -108,11 +125,13 @@ export interface VitestRunner {
*
* @see https://vitest.dev/advanced/runner.html#your-task-function
*/
- extendTaskContext?(context: TaskContext): ExtendedContext
+ extendTaskContext?: (
+ context: TaskContext
+ ) => ExtendedContext
/**
* Called, when files are imported. Can be called in two situations: when collecting tests and when importing setup files.
*/
- importFile(filepath: string, source: VitestRunnerImportSource): unknown
+ importFile: (filepath: string, source: VitestRunnerImportSource) => unknown
/**
* Publicly available configuration.
*/
diff --git a/packages/runner/src/types/tasks.ts b/packages/runner/src/types/tasks.ts
index 199ff8dc8..57895ee11 100644
--- a/packages/runner/src/types/tasks.ts
+++ b/packages/runner/src/types/tasks.ts
@@ -193,19 +193,19 @@ export interface TestOptions {
interface ExtendedAPI {
each: TestEachFunction
- skipIf(condition: any): ChainableTestAPI
- runIf(condition: any): ChainableTestAPI
+ skipIf: (condition: any) => ChainableTestAPI
+ runIf: (condition: any) => ChainableTestAPI
}
export type CustomAPI = ChainableTestAPI & ExtendedAPI & {
- extend = {}>(fixtures: Fixtures): CustomAPI<{
+ extend: = {}>(fixtures: Fixtures) => CustomAPI<{
[K in keyof T | keyof ExtraContext]:
K extends keyof T ? T[K] :
K extends keyof ExtraContext ? ExtraContext[K] : never }>
}
export type TestAPI = ChainableTestAPI & ExtendedAPI & {
- extend = {}>(fixtures: Fixtures): TestAPI<{
+ extend: = {}>(fixtures: Fixtures) => TestAPI<{
[K in keyof T | keyof ExtraContext]:
K extends keyof T ? T[K] :
K extends keyof ExtraContext ? ExtraContext[K] : never }>
@@ -236,8 +236,8 @@ type ChainableSuiteAPI = ChainableFunction<
export type SuiteAPI = ChainableSuiteAPI & {
each: SuiteEachFunction
- skipIf(condition: any): ChainableSuiteAPI
- runIf(condition: any): ChainableSuiteAPI
+ skipIf: (condition: any) => ChainableSuiteAPI
+ runIf: (condition: any) => ChainableSuiteAPI
}
export type HookListener = (...args: T) => Awaitable
diff --git a/packages/snapshot/README.md b/packages/snapshot/README.md
index a89d9fe59..4c4ecda22 100644
--- a/packages/snapshot/README.md
+++ b/packages/snapshot/README.md
@@ -76,4 +76,4 @@ manager.add(result)
// and then read the summary
console.log(manager.summary)
-```
\ No newline at end of file
+```
diff --git a/packages/snapshot/src/types/environment.ts b/packages/snapshot/src/types/environment.ts
index 57776314f..ff79cc1db 100644
--- a/packages/snapshot/src/types/environment.ts
+++ b/packages/snapshot/src/types/environment.ts
@@ -1,11 +1,11 @@
export interface SnapshotEnvironment {
- getVersion(): string
- getHeader(): string
- resolvePath(filepath: string): Promise
- resolveRawPath(testPath: string, rawPath: string): Promise
- saveSnapshotFile(filepath: string, snapshot: string): Promise
- readSnapshotFile(filepath: string): Promise
- removeSnapshotFile(filepath: string): Promise
+ getVersion: () => string
+ getHeader: () => string
+ resolvePath: (filepath: string) => Promise
+ resolveRawPath: (testPath: string, rawPath: string) => Promise
+ saveSnapshotFile: (filepath: string, snapshot: string) => Promise
+ readSnapshotFile: (filepath: string) => Promise
+ removeSnapshotFile: (filepath: string) => Promise
}
export interface SnapshotEnvironmentOptions {
diff --git a/packages/spy/src/index.ts b/packages/spy/src/index.ts
index 023b70957..6e3315b56 100644
--- a/packages/spy/src/index.ts
+++ b/packages/spy/src/index.ts
@@ -113,11 +113,11 @@ export interface MockInstance {
/**
* Use it to return the name given to mock with method `.mockName(name)`.
*/
- getMockName(): string
+ getMockName: () => string
/**
* Sets internal mock name. Useful to see the name of the mock if an assertion fails.
*/
- mockName(n: string): this
+ mockName: (n: string) => this
/**
* Current context of the mock. It stores information about all invocation calls, instances, and results.
*/
@@ -127,19 +127,19 @@ export interface MockInstance {
*
* It is useful if you need to clean up mock between different assertions.
*/
- mockClear(): this
+ mockClear: () => this
/**
* Does what `mockClear` does and makes inner implementation an empty function (returning `undefined` when invoked). This also resets all "once" implementations.
*
* This is useful when you want to completely reset a mock to the default state.
*/
- mockReset(): this
+ mockReset: () => this
/**
* Does what `mockReset` does and restores inner implementation to the original function.
*
* Note that restoring mock from `vi.fn()` will set implementation to an empty function that returns `undefined`. Restoring a `vi.fn(impl)` will restore implementation to `impl`.
*/
- mockRestore(): void
+ mockRestore: () => void
/**
* Returns current mock implementation if there is one.
*
@@ -147,14 +147,14 @@ export interface MockInstance {
*
* If mock was created with `vi.spyOn`, it will return `undefined` unless a custom implementation was provided.
*/
- getMockImplementation(): ((...args: TArgs) => TReturns) | undefined
+ getMockImplementation: () => ((...args: TArgs) => TReturns) | undefined
/**
* Accepts a function that will be used as an implementation of the mock.
* @example
* const increment = vi.fn().mockImplementation(count => count + 1);
* expect(increment(3)).toBe(4);
*/
- mockImplementation(fn: ((...args: TArgs) => TReturns)): this
+ mockImplementation: (fn: ((...args: TArgs) => TReturns)) => this
/**
* Accepts a function that will be used as a mock implementation during the next call. Can be chained so that multiple function calls produce different results.
* @example
@@ -162,7 +162,7 @@ export interface MockInstance {
* expect(fn(3)).toBe(4);
* expect(fn(3)).toBe(3);
*/
- mockImplementationOnce(fn: ((...args: TArgs) => TReturns)): this
+ mockImplementationOnce: (fn: ((...args: TArgs) => TReturns)) => this
/**
* Overrides the original mock implementation temporarily while the callback is being executed.
* @example
@@ -174,15 +174,15 @@ export interface MockInstance {
*
* myMockFn() // 'original'
*/
- withImplementation(fn: ((...args: TArgs) => TReturns), cb: () => T): T extends Promise ? Promise : this
+ withImplementation: (fn: ((...args: TArgs) => TReturns), cb: () => T) => T extends Promise ? Promise : this
/**
* Use this if you need to return `this` context from the method without invoking actual implementation.
*/
- mockReturnThis(): this
+ mockReturnThis: () => this
/**
* Accepts a value that will be returned whenever the mock function is called.
*/
- mockReturnValue(obj: TReturns): this
+ mockReturnValue: (obj: TReturns) => this
/**
* Accepts a value that will be returned during the next function call. If chained, every consecutive call will return the specified value.
*
@@ -197,14 +197,14 @@ export interface MockInstance {
* // 'first call', 'second call', 'default'
* console.log(myMockFn(), myMockFn(), myMockFn())
*/
- mockReturnValueOnce(obj: TReturns): this
+ mockReturnValueOnce: (obj: TReturns) => this
/**
* Accepts a value that will be resolved when async function is called.
* @example
* const asyncMock = vi.fn().mockResolvedValue(42)
* asyncMock() // Promise<42>
*/
- mockResolvedValue(obj: Awaited): this
+ mockResolvedValue: (obj: Awaited) => this
/**
* Accepts a value that will be resolved during the next function call. If chained, every consecutive call will resolve specified value.
* @example
@@ -217,14 +217,14 @@ export interface MockInstance {
* // Promise<'first call'>, Promise<'second call'>, Promise<'default'>
* console.log(myMockFn(), myMockFn(), myMockFn())
*/
- mockResolvedValueOnce(obj: Awaited): this
+ mockResolvedValueOnce: (obj: Awaited) => this
/**
* Accepts an error that will be rejected when async function is called.
* @example
* const asyncMock = vi.fn().mockRejectedValue(new Error('Async error'))
* await asyncMock() // throws 'Async error'
*/
- mockRejectedValue(obj: any): this
+ mockRejectedValue: (obj: any) => this
/**
* Accepts a value that will be rejected during the next function call. If chained, every consecutive call will reject specified value.
* @example
@@ -236,7 +236,7 @@ export interface MockInstance {
* await asyncMock() // first call
* await asyncMock() // throws "Async error"
*/
- mockRejectedValueOnce(obj: any): this
+ mockRejectedValueOnce: (obj: any) => this
}
export interface Mock extends MockInstance {
diff --git a/packages/ui/cypress/support/mount.ts b/packages/ui/cypress/support/mount.ts
index d1fd06678..13b220dab 100644
--- a/packages/ui/cypress/support/mount.ts
+++ b/packages/ui/cypress/support/mount.ts
@@ -28,7 +28,7 @@ declare global {
/**
* Install all vue plugins and globals then mount
*/
- mount(comp: Component, options?: unknown): Cypress.Chainable
+ mount: (comp: Component, options?: unknown) => Cypress.Chainable
}
}
}
diff --git a/packages/vite-node/src/hmr/emitter.ts b/packages/vite-node/src/hmr/emitter.ts
index 924a8030d..06afe9862 100644
--- a/packages/vite-node/src/hmr/emitter.ts
+++ b/packages/vite-node/src/hmr/emitter.ts
@@ -4,10 +4,9 @@ import type { HMRPayload, Plugin } from 'vite'
export type EventType = string | symbol
export type Handler = (event: T) => void
export interface Emitter> {
- on(type: Key, handler: Handler): void
- off(type: Key, handler?: Handler): void
- emit(type: Key, event: Events[Key]): void
- emit(type: undefined extends Events[Key] ? Key : never): void
+ on: (type: Key, handler: Handler) => void
+ off: (type: Key, handler?: Handler) => void
+ emit: ((type: Key, event: Events[Key]) => void) & ((type: undefined extends Events[Key] ? Key : never) => void)
}
export type HMREmitter = Emitter<{
@@ -22,7 +21,7 @@ declare module 'vite' {
export function createHmrEmitter(): HMREmitter {
const emitter = new EventEmitter()
- return emitter
+ return emitter as HMREmitter
}
export function viteNodeHmrPlugin(): Plugin {
diff --git a/packages/vite-node/src/source-map-handler.ts b/packages/vite-node/src/source-map-handler.ts
index f71af8e83..383416906 100644
--- a/packages/vite-node/src/source-map-handler.ts
+++ b/packages/vite-node/src/source-map-handler.ts
@@ -225,7 +225,7 @@ function mapEvalOrigin(origin: string): string {
}
interface CallSite extends NodeJS.CallSite {
- getScriptNameOrSourceURL(): string
+ getScriptNameOrSourceURL: () => string
}
// This is copied almost verbatim from the V8 source code at
diff --git a/packages/vitest/package.json b/packages/vitest/package.json
index 8abd6af8b..7b5550e66 100644
--- a/packages/vitest/package.json
+++ b/packages/vitest/package.json
@@ -121,22 +121,22 @@
"jsdom": "*"
},
"peerDependenciesMeta": {
- "@types/node": {
+ "@edge-runtime/vm": {
"optional": true
},
- "@vitest/ui": {
+ "@types/node": {
"optional": true
},
"@vitest/browser": {
"optional": true
},
- "happy-dom": {
+ "@vitest/ui": {
"optional": true
},
- "jsdom": {
+ "happy-dom": {
"optional": true
},
- "@edge-runtime/vm": {
+ "jsdom": {
"optional": true
}
},
diff --git a/packages/vitest/src/api/types.ts b/packages/vitest/src/api/types.ts
index 6dba431c2..333182a93 100644
--- a/packages/vitest/src/api/types.ts
+++ b/packages/vitest/src/api/types.ts
@@ -7,36 +7,36 @@ export interface TransformResultWithSource extends TransformResult {
}
export interface WebSocketHandlers {
- onUnhandledError(error: unknown, type: string): Promise
- onCollected(files?: File[]): Promise
- onTaskUpdate(packs: TaskResultPack[]): void
- onAfterSuiteRun(meta: AfterSuiteRunMeta): void
- onCancel(reason: CancelReason): void
- getCountOfFailedTests(): number
- sendLog(log: UserConsoleLog): void
- getFiles(): File[]
- getPaths(): string[]
- getConfig(): ResolvedConfig
- resolveSnapshotPath(testPath: string): string
- resolveSnapshotRawPath(testPath: string, rawPath: string): string
- getModuleGraph(id: string): Promise
- getTransformResult(id: string): Promise
- readSnapshotFile(id: string): Promise
- readTestFile(id: string): Promise
- saveTestFile(id: string, content: string): Promise
- saveSnapshotFile(id: string, content: string): Promise
- removeSnapshotFile(id: string): Promise
- snapshotSaved(snapshot: SnapshotResult): void
- rerun(files: string[]): Promise
- updateSnapshot(file?: File): Promise
- getProvidedContext(): ProvidedContext
- getUnhandledErrors(): unknown[]
+ onUnhandledError: (error: unknown, type: string) => Promise
+ onCollected: (files?: File[]) => Promise
+ onTaskUpdate: (packs: TaskResultPack[]) => void
+ onAfterSuiteRun: (meta: AfterSuiteRunMeta) => void
+ onCancel: (reason: CancelReason) => void
+ getCountOfFailedTests: () => number
+ sendLog: (log: UserConsoleLog) => void
+ getFiles: () => File[]
+ getPaths: () => string[]
+ getConfig: () => ResolvedConfig
+ resolveSnapshotPath: (testPath: string) => string
+ resolveSnapshotRawPath: (testPath: string, rawPath: string) => string
+ getModuleGraph: (id: string) => Promise
+ getTransformResult: (id: string) => Promise
+ readSnapshotFile: (id: string) => Promise
+ readTestFile: (id: string) => Promise
+ saveTestFile: (id: string, content: string) => Promise
+ saveSnapshotFile: (id: string, content: string) => Promise
+ removeSnapshotFile: (id: string) => Promise
+ snapshotSaved: (snapshot: SnapshotResult) => void
+ rerun: (files: string[]) => Promise
+ updateSnapshot: (file?: File) => Promise
+ getProvidedContext: () => ProvidedContext
+ getUnhandledErrors: () => unknown[]
- finishBrowserTests(): void
- getBrowserFiles(): string[]
- debug(...args: string[]): void
+ finishBrowserTests: () => void
+ getBrowserFiles: () => string[]
+ debug: (...args: string[]) => void
}
export interface WebSocketEvents extends Pick {
- onCancel(reason: CancelReason): void
+ onCancel: (reason: CancelReason) => void
}
diff --git a/packages/vitest/src/integrations/vi.ts b/packages/vitest/src/integrations/vi.ts
index 052db9b9f..72b438fa8 100644
--- a/packages/vitest/src/integrations/vi.ts
+++ b/packages/vitest/src/integrations/vi.ts
@@ -18,76 +18,76 @@ export interface VitestUtils {
/**
* Checks if fake timers are enabled.
*/
- isFakeTimers(): boolean
+ isFakeTimers: () => boolean
/**
* This method wraps all further calls to timers until [`vi.useRealTimers()`](https://vitest.dev/api/vi#vi-userealtimers) is called.
*/
- useFakeTimers(config?: FakeTimerInstallOpts): VitestUtils
+ useFakeTimers: (config?: FakeTimerInstallOpts) => VitestUtils
/**
* Restores mocked timers to their original implementations. All timers that were scheduled before will be discarded.
*/
- useRealTimers(): VitestUtils
+ useRealTimers: () => VitestUtils
/**
* This method will call every timer that was initiated after [`vi.useFakeTimers`](https://vitest.dev/api/vi#vi-usefaketimers) call.
* It will not fire any timer that was initiated during its call.
*/
- runOnlyPendingTimers(): VitestUtils
+ runOnlyPendingTimers: () => VitestUtils
/**
* This method will asynchronously call every timer that was initiated after [`vi.useFakeTimers`](https://vitest.dev/api/vi#vi-usefaketimers) call, even asynchronous ones.
* It will not fire any timer that was initiated during its call.
*/
- runOnlyPendingTimersAsync(): Promise
+ runOnlyPendingTimersAsync: () => Promise
/**
* This method will invoke every initiated timer until the timer queue is empty. It means that every timer called during `runAllTimers` will be fired.
* If you have an infinite interval, it will throw after 10,000 tries (can be configured with [`fakeTimers.loopLimit`](https://vitest.dev/config/#faketimers-looplimit)).
*/
- runAllTimers(): VitestUtils
+ runAllTimers: () => VitestUtils
/**
* This method will asynchronously invoke every initiated timer until the timer queue is empty. It means that every timer called during `runAllTimersAsync` will be fired even asynchronous timers.
* If you have an infinite interval, it will throw after 10 000 tries (can be configured with [`fakeTimers.loopLimit`](https://vitest.dev/config/#faketimers-looplimit)).
*/
- runAllTimersAsync(): Promise
+ runAllTimersAsync: () => Promise
/**
* Calls every microtask that was queued by `process.nextTick`. This will also run all microtasks scheduled by themselves.
*/
- runAllTicks(): VitestUtils
+ runAllTicks: () => VitestUtils
/**
* This method will invoke every initiated timer until the specified number of milliseconds is passed or the queue is empty - whatever comes first.
*/
- advanceTimersByTime(ms: number): VitestUtils
+ advanceTimersByTime: (ms: number) => VitestUtils
/**
* This method will invoke every initiated timer until the specified number of milliseconds is passed or the queue is empty - whatever comes first. This will include and await asynchronously set timers.
*/
- advanceTimersByTimeAsync(ms: number): Promise
+ advanceTimersByTimeAsync: (ms: number) => Promise
/**
* Will call next available timer. Useful to make assertions between each timer call. You can chain call it to manage timers by yourself.
*/
- advanceTimersToNextTimer(): VitestUtils
+ advanceTimersToNextTimer: () => VitestUtils
/**
* Will call next available timer and wait until it's resolved if it was set asynchronously. Useful to make assertions between each timer call.
*/
- advanceTimersToNextTimerAsync(): Promise
+ advanceTimersToNextTimerAsync: () => Promise
/**
* Get the number of waiting timers.
*/
- getTimerCount(): number
+ getTimerCount: () => number
/**
* If fake timers are enabled, this method simulates a user changing the system clock (will affect date related API like `hrtime`, `performance.now` or `new Date()`) - however, it will not fire any timers.
* If fake timers are not enabled, this method will only mock `Date.*` and `new Date()` calls.
*/
- setSystemTime(time: number | string | Date): VitestUtils
+ setSystemTime: (time: number | string | Date) => VitestUtils
/**
* Returns mocked current date that was set using `setSystemTime`. If date is not mocked the method will return `null`.
*/
- getMockedSystemTime(): Date | null
+ getMockedSystemTime: () => Date | null
/**
* When using `vi.useFakeTimers`, `Date.now` calls are mocked. If you need to get real time in milliseconds, you can call this function.
*/
- getRealSystemTime(): number
+ getRealSystemTime: () => number
/**
* Removes all timers that are scheduled to run. These timers will never run in the future.
*/
- clearAllTimers(): VitestUtils
+ clearAllTimers: () => VitestUtils
/**
* Creates a spy on a method or getter/setter of an object similar to [`vi.fn()`](https://vitest.dev/api/vi#vi-fn). It returns a [mock function](https://vitest.dev/api/mock).
@@ -172,7 +172,7 @@ export interface VitestUtils {
*
* If used with [`vi.mock`](https://vitest.dev/api/vi#vi-mock), both will be hoisted in the order they are defined in.
*/
- hoisted(factory: () => T): T
+ hoisted: (factory: () => T) => T
/**
* Mocks every import call to the module even if it was already statically imported.
@@ -184,7 +184,7 @@ export interface VitestUtils {
* @param path Path to the module. Can be aliased, if your Vitest config supports it
* @param factory Mocked module factory. The result of this function will be an exports object
*/
- mock(path: string, factory?: MockFactoryWithHelper): void
+ mock: (path: string, factory?: MockFactoryWithHelper) => void
/**
* Removes module from mocked registry. All calls to import will return the original module even if it was mocked before.
@@ -192,7 +192,7 @@ export interface VitestUtils {
* This call is hoisted to the top of the file, so it will only unmock modules that were defined in `setupFiles`, for example.
* @param path Path to the module. Can be aliased, if your Vitest config supports it
*/
- unmock(path: string): void
+ unmock: (path: string) => void
/**
* Mocks every subsequent [dynamic import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import) call.
@@ -203,14 +203,14 @@ export interface VitestUtils {
* @param path Path to the module. Can be aliased, if your Vitest config supports it
* @param factory Mocked module factory. The result of this function will be an exports object
*/
- doMock(path: string, factory?: MockFactoryWithHelper): void
+ doMock: (path: string, factory?: MockFactoryWithHelper) => void
/**
* Removes module from mocked registry. All subsequent calls to import will return original module.
*
* Unlike [`vi.unmock`](https://vitest.dev/api/vi#vi-unmock), this method is not hoisted to the top of the file.
* @param path Path to the module. Can be aliased, if your Vitest config supports it
*/
- doUnmock(path: string): void
+ doUnmock: (path: string) => void
/**
* Imports module, bypassing all checks if it should be mocked.
@@ -223,7 +223,7 @@ export interface VitestUtils {
* })
* @param path Path to the module. Can be aliased, if your config supports it
*/
- importActual(path: string): Promise
+ importActual: (path: string) => Promise
/**
* Imports a module with all of its properties and nested properties mocked.
@@ -236,7 +236,7 @@ export interface VitestUtils {
* @param path Path to the module. Can be aliased, if your config supports it
* @returns Fully mocked module
*/
- importMock(path: string): Promise>
+ importMock: (path: string) => Promise>
/**
* Type helper for TypeScript. Just returns the object that was passed.
@@ -255,60 +255,54 @@ export interface VitestUtils {
* @param deep If the object is deeply mocked
* @param options If the object is partially or deeply mocked
*/
- mocked(item: T, deep?: false): MaybeMocked
- mocked(item: T, deep: true): MaybeMockedDeep
- mocked(item: T, options: { partial?: false; deep?: false }): MaybeMocked
- mocked(item: T, options: { partial?: false; deep: true }): MaybeMockedDeep
- mocked(item: T, options: { partial: true; deep?: false }): MaybePartiallyMocked
- mocked(item: T, options: { partial: true; deep: true }): MaybePartiallyMockedDeep
- mocked(item: T): MaybeMocked
+ mocked: ((item: T, deep?: false) => MaybeMocked) & ((item: T, deep: true) => MaybeMockedDeep) & ((item: T, options: { partial?: false; deep?: false }) => MaybeMocked) & ((item: T, options: { partial?: false; deep: true }) => MaybeMockedDeep