# Vitest
> This guide lists advanced APIs to run tests via a Node.js script. If you just want to [run tests](/guide/), you probably don't need this. It is primarily used by library authors.
---
# Source: https://vitest.dev/guide/advanced.md
---
url: /guide/advanced.md
---
# Getting Started advanced {#getting-started}
::: warning
This guide lists advanced APIs to run tests via a Node.js script. If you just want to [run tests](/guide/), you probably don't need this. It is primarily used by library authors.
:::
You can import any method from the `vitest/node` entry-point.
## startVitest
```ts
function startVitest(
mode: VitestRunMode,
cliFilters: string[] = [],
options: CliOptions = {},
viteOverrides?: ViteUserConfig,
vitestOptions?: VitestOptions,
): Promise
```
You can start running Vitest tests using its Node API:
```js
import { startVitest } from 'vitest/node'
const vitest = await startVitest('test')
await vitest.close()
```
`startVitest` function returns [`Vitest`](/api/advanced/vitest) instance if tests can be started.
If watch mode is not enabled, Vitest will call `close` method automatically.
If watch mode is enabled and the terminal supports TTY, Vitest will register console shortcuts.
You can pass down a list of filters as a second argument. Vitest will run only tests that contain at least one of the passed-down strings in their file path.
Additionally, you can use the third argument to pass in CLI arguments, which will override any test config options. Alternatively, you can pass in the complete Vite config as the fourth argument, which will take precedence over any other user-defined options.
After running the tests, you can get the results from the [`state.getTestModules`](/api/advanced/test-module) API:
```ts
import type { TestModule } from 'vitest/node'
const vitest = await startVitest('test')
console.log(vitest.state.getTestModules()) // [TestModule]
```
::: tip
The ["Running Tests"](/guide/advanced/tests#startvitest) guide has a usage example.
:::
## createVitest
```ts
function createVitest(
mode: VitestRunMode,
options: CliOptions,
viteOverrides: ViteUserConfig = {},
vitestOptions: VitestOptions = {},
): Promise
```
You can create Vitest instance by using `createVitest` function. It returns the same [`Vitest`](/api/advanced/vitest) instance as `startVitest`, but it doesn't start tests and doesn't validate installed packages.
```js
import { createVitest } from 'vitest/node'
const vitest = await createVitest('test', {
watch: false,
})
```
::: tip
The ["Running Tests"](/guide/advanced/tests#createvitest) guide has a usage example.
:::
## resolveConfig
```ts
function resolveConfig(
options: UserConfig = {},
viteOverrides: ViteUserConfig = {},
): Promise<{
vitestConfig: ResolvedConfig
viteConfig: ResolvedViteConfig
}>
```
This method resolves the config with custom parameters. If no parameters are given, the `root` will be `process.cwd()`.
```ts
import { resolveConfig } from 'vitest/node'
// vitestConfig only has resolved "test" properties
const { vitestConfig, viteConfig } = await resolveConfig({
mode: 'custom',
configFile: false,
resolve: {
conditions: ['custom']
},
test: {
setupFiles: ['/my-setup-file.js'],
pool: 'threads',
},
})
```
::: info
Due to how Vite's `createServer` works, Vitest has to resolve the config during the plugin's `configResolve` hook. Therefore, this method is not actually used internally and is exposed exclusively as a public API.
If you pass down the config to the `startVitest` or `createVitest` APIs, Vitest will still resolve the config again.
:::
::: warning
The `resolveConfig` doesn't resolve `projects`. To resolve projects configs, Vitest needs an established Vite server.
Also note that `viteConfig.test` will not be fully resolved. If you need Vitest config, use `vitestConfig` instead.
:::
## parseCLI
```ts
function parseCLI(argv: string | string[], config: CliParseOptions = {}): {
filter: string[]
options: CliOptions
}
```
You can use this method to parse CLI arguments. It accepts a string (where arguments are split by a single space) or a strings array of CLI arguments in the same format that Vitest CLI uses. It returns a filter and `options` that you can later pass down to `createVitest` or `startVitest` methods.
```ts
import { parseCLI } from 'vitest/node'
const result = parseCLI('vitest ./files.ts --coverage --browser=chrome')
result.options
// {
// coverage: { enabled: true },
// browser: { name: 'chrome', enabled: true }
// }
result.filter
// ['./files.ts']
```
---
# Source: https://vitest.dev/config/alias.md
---
url: /config/alias.md
---
# alias
* **Type:** `Record | Array<{ find: string | RegExp, replacement: string, customResolver?: ResolverFunction | ResolverObject }>`
Define custom aliases when running inside tests. They will be merged with aliases from `resolve.alias`.
::: warning
Vitest uses Vite SSR primitives to run tests which has [certain pitfalls](https://vitejs.dev/guide/ssr.html#ssr-externals).
1. Aliases affect only modules imported directly with an `import` keyword by an [inlined](#server-deps-inline) module (all source code is inlined by default).
2. Vitest does not support aliasing `require` calls.
3. If you are aliasing an external dependency (e.g., `react` -> `preact`), you may want to alias the actual `node_modules` packages instead to make it work for externalized dependencies. Both [Yarn](https://classic.yarnpkg.com/en/docs/cli/add/#toc-yarn-add-alias) and [pnpm](https://pnpm.io/aliases/) support aliasing via the `npm:` prefix.
:::
---
# Source: https://vitest.dev/config/allowonly.md
---
url: /config/allowonly.md
---
# allowOnly
* **Type**: `boolean`
* **Default**: `!process.env.CI`
* **CLI:** `--allowOnly`, `--allowOnly=false`
By default, Vitest does not permit tests marked with the [`only`](/api/#test-only) flag in Continuous Integration (CI) environments. Conversely, in local development environments, Vitest allows these tests to run.
::: info
Vitest uses [`std-env`](https://www.npmjs.com/package/std-env) package to detect the environment.
:::
You can customize this behavior by explicitly setting the `allowOnly` option to either `true` or `false`.
::: code-group
```js [vitest.config.js]
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
allowOnly: true,
},
})
```
```bash [CLI]
vitest --allowOnly
```
:::
When enabled, Vitest will not fail the test suite if tests marked with [`only`](/api/#test-only) are detected, including in CI environments.
When disabled, Vitest will fail the test suite if tests marked with [`only`](/api/#test-only) are detected, including in local development environments.
---
# Source: https://vitest.dev/api.md
# Source: https://vitest.dev/config/browser/api.md
# Source: https://vitest.dev/config/api.md
---
url: /config/api.md
---
# api
* **Type:** `boolean | number`
* **Default:** `false`
* **CLI:** `--api`, `--api.port`, `--api.host`, `--api.strictPort`
Listen to port and serve API for [the UI](/guide/ui) or [browser server](/guide/browser/). When set to `true`, the default port is `51204`.
---
# Source: https://vitest.dev/api/advanced/artifacts.md
---
url: /api/advanced/artifacts.md
---
# Test Artifacts 4.0.11
::: warning
This is an advanced API. As a user, you most likely want to use [test annotations](/guide/test-annotations) to add notes or context to your tests instead. This is primarily used internally and by library authors.
:::
Test artifacts allow attaching or recording structured data, files, or metadata during test execution. This is a low-level feature primarily designed for:
* Internal use ([`annotate`](/guide/test-annotations) is built on top of the artifact system)
* Framework authors creating custom testing tools on top of Vitest
Each artifact includes:
* A type discriminator which is a unique identifier for the artifact type
* Custom data, can be any relevant information
* Optional attachments, either files or inline content associated with the artifact
* A source code location indicating where the artifact was created
Vitest automatically manages attachment serialization (files are copied to [`attachmentsDir`](/config/#attachmentsdir)) and injects source location metadata, so you can focus on the data you want to record. All artifacts **must** extend from [`TestArtifactBase`](#testartifactbase) and all attachments from [`TestAttachment`](#testattachment) to be correctly handled internally.
## API
### `recordArtifact` {#recordartifact}
::: warning
`recordArtifact` is an experimental API. Breaking changes might not follow SemVer, please pin Vitest's version when using it.
The API surface may change based on feedback. We encourage you to try it out and share your experience with the team.
:::
```ts
function recordArtifact(task: Test, artifact: Artifact): Promise
```
The `recordArtifact` function records an artifact during test execution and returns it. It expects a [task](/api/advanced/runner#tasks) as the first parameter and an object assignable to [`TestArtifact`](#testartifact) as the second.
This function has to be used within a test, and the test has to still be running. Recording after test completion will throw an error.
When an artifact is recorded on a test, it emits an `onTestArtifactRecord` runner event and a [`onTestCaseArtifactRecord` reporter event](/api/advanced/reporters#ontestcaseartifactrecord). To retrieve recorded artifacts from a test case, use the [`artifacts()`](/api/advanced/test-case#artifacts) method.
Note: annotations, [even though they're built on top of this feature](#relationship-with-annotations), won't appear in the `task.artifacts` array for backwards compatibility reasons until the next major version.
### `TestArtifact`
The `TestArtifact` type is a union containing all artifacts Vitest can produce, including custom ones. All artifacts extend from [`TestArtifactBase`](#testartifactbase)
### `TestArtifactBase` {#testartifactbase}
```ts
export interface TestArtifactBase {
/** File or data attachments associated with this artifact */
attachments?: TestAttachment[]
/** Source location where this artifact was created */
location?: TestArtifactLocation
}
```
The `TestArtifactBase` interface is the base for all test artifacts.
Extend this interface when creating custom test artifacts. Vitest automatically manages the `attachments` array and injects the `location` property to indicate where the artifact was created in your test code.
### `TestAttachment`
```ts
export interface TestAttachment {
/** MIME type of the attachment (e.g., 'image/png', 'text/plain') */
contentType?: string
/** File system path to the attachment */
path?: string
/** Inline attachment content as a string or raw binary data */
body?: string | Uint8Array
}
```
The `TestAttachment` interface represents a file or data attachment associated with a test artifact.
Attachments can be either file-based (via `path`) or inline content (via `body`). The `contentType` helps consumers understand how to interpret the attachment data.
### `TestArtifactLocation`
```ts
export interface TestArtifactLocation {
/** Line number in the source file (1-indexed) */
line: number
/** Column number in the line (1-indexed) */
column: number
/** Path to the source file */
file: string
}
```
The `TestArtifactLocation` interface represents the source code location information for a test artifact. It indicates where in the source code the artifact originated from.
### `TestArtifactRegistry`
The `TestArtifactRegistry` interface is a registry for custom test artifact types.
Augmenting this interface using [TypeScript's module augmentation feature](https://typescriptlang.org/docs/handbook/declaration-merging#module-augmentation) allows registering custom artifact types that tests can produce.
Each custom artifact should extend [`TestArtifactBase`](#testartifactbase) and include a unique `type` discriminator property.
Here are a few guidelines or best practices to follow:
* Try using a `Symbol` as the **registry key** to guarantee uniqueness
* The `type` property should follow the pattern `'package-name:artifact-name'`, **`'internal:'` is a reserved prefix**
* Use `attachments` to include files or data; extend [`TestAttachment`](#testattachment) for custom metadata
* `location` property is automatically injected
## Custom Artifacts
To use and manage artifacts in a type-safe manner, you need to create its type and register it:
```ts
import type { TestArtifactBase, TestAttachment } from 'vitest'
interface A11yReportAttachment extends TestAttachment {
contentType: 'text/html'
path: string
}
interface AccessibilityArtifact extends TestArtifactBase {
type: 'a11y:report'
passed: boolean
wcagLevel: 'A' | 'AA' | 'AAA'
attachments: [A11yReportAttachment]
}
const a11yReportKey = Symbol('report')
declare module 'vitest' {
interface TestArtifactRegistry {
[a11yReportKey]: AccessibilityArtifact
}
}
```
As long as the types are assignable to their bases and don't have errors, everything should work fine and you should be able to record artifacts using [`recordArtifact`](#recordartifact):
```ts
async function toBeAccessible(
this: MatcherState,
actual: Element,
wcagLevel: 'A' | 'AA' | 'AAA' = 'AA'
): AsyncExpectationResult {
const report = await runAccessibilityAudit(actual, wcagLevel)
await recordArtifact(this.task, {
type: 'a11y:report',
passed: report.violations.length === 0,
wcagLevel,
attachments: [{
contentType: 'text/html',
path: report.path,
}],
})
return {
pass: violations.length === 0,
message: () => `Found ${report.violations.length} accessibility violation(s)`
}
}
```
## Relationship with Annotations
Test annotations are built on top of the artifact system. When using annotations in tests, they create `internal:annotation` artifacts under the hood. However, annotations are:
* Simpler to use
* Designed for end-users, not developers
Use annotations if you just want to add notes to your tests. Use artifacts if you need custom data.
---
# Source: https://vitest.dev/api/assert-type.md
---
url: /api/assert-type.md
---
# assertType
::: warning
During runtime this function doesn't do anything. To [enable typechecking](/guide/testing-types#run-typechecking), don't forget to pass down `--typecheck` flag.
:::
* **Type:** `(value: T): void`
You can use this function as an alternative for [`expectTypeOf`](/api/expect-typeof) to easily assert that the argument type is equal to the generic provided.
```ts
import { assertType } from 'vitest'
function concat(a: string, b: string): string
function concat(a: number, b: number): number
function concat(a: string | number, b: string | number): string | number
assertType(concat('a', 'b'))
assertType(concat(1, 2))
// @ts-expect-error wrong types
assertType(concat('a', 2))
```
---
# Source: https://vitest.dev/api/assert.md
---
url: /api/assert.md
---
# assert
Vitest reexports the `assert` method from [`chai`](https://www.chaijs.com/api/assert/) for verifying invariants.
## assert
* **Type:** `(expression: any, message?: string) => asserts expression`
Assert that the given `expression` is truthy, otherwise the assertion fails.
```ts
import { assert, test } from 'vitest'
test('assert', () => {
assert('foo' !== 'bar', 'foo should not be equal to bar')
})
```
## fail
* **Type:**
* `(message?: string) => never`
* `(actual: T, expected: T, message?: string, operator?: string) => never`
Force an assertion failure.
```ts
import { assert, test } from 'vitest'
test('assert.fail', () => {
assert.fail('error message on failure')
assert.fail('foo', 'bar', 'foo is not bar', '===')
})
```
## isOk
* **Type:** `(value: T, message?: string) => asserts value`
* **Alias** `ok`
Assert that the given `value` is truthy.
```ts
import { assert, test } from 'vitest'
test('assert.isOk', () => {
assert.isOk('foo', 'every truthy is ok')
assert.isOk(false, 'this will fail since false is not truthy')
})
```
## isNotOk
* **Type:** `(value: T, message?: string) => void`
* **Alias** `notOk`
Assert that the given `value` is falsy.
```ts
import { assert, test } from 'vitest'
test('assert.isNotOk', () => {
assert.isNotOk('foo', 'this will fail, every truthy is not ok')
assert.isNotOk(false, 'this will pass since false is falsy')
})
```
## equal
* **Type:** `(actual: T, expected: T, message?: string) => void`
Asserts non-strict equality (==) of `actual` and `expected`.
```ts
import { assert, test } from 'vitest'
test('assert.equal', () => {
assert.equal(Math.sqrt(4), '2')
})
```
## notEqual
* **Type:** `(actual: T, expected: T, message?: string) => void`
Asserts non-strict inequality (!=) of `actual` and `expected`.
```ts
import { assert, test } from 'vitest'
test('assert.equal', () => {
assert.notEqual(Math.sqrt(4), 3)
})
```
## strictEqual
* **Type:** `(actual: T, expected: T, message?: string) => void`
Asserts strict equality (===) of `actual` and `expected`.
```ts
import { assert, test } from 'vitest'
test('assert.strictEqual', () => {
assert.strictEqual(Math.sqrt(4), 2)
})
```
## deepEqual
* **Type:** `(actual: T, expected: T, message?: string) => void`
Asserts that `actual` is deeply equal to `expected`.
```ts
import { assert, test } from 'vitest'
test('assert.deepEqual', () => {
assert.deepEqual({ color: 'green' }, { color: 'green' })
})
```
## notDeepEqual
* **Type:** `(actual: T, expected: T, message?: string) => void`
Assert that `actual` is not deeply equal to `expected`.
```ts
import { assert, test } from 'vitest'
test('assert.notDeepEqual', () => {
assert.notDeepEqual({ color: 'green' }, { color: 'red' })
})
```
## isAbove
* **Type:** `(valueToCheck: number, valueToBeAbove: number, message?: string) => void`
Assert that `valueToCheck` is strictly greater than (>) `valueToBeAbove`.
```ts
import { assert, test } from 'vitest'
test('assert.isAbove', () => {
assert.isAbove(5, 2, '5 is strictly greater than 2')
})
```
## isAtLeast
* **Type:** `(valueToCheck: number, valueToBeAtLeast: number, message?: string) => void`
Assert that `valueToCheck` is greater than or equal to (>=) `valueToBeAtLeast`.
```ts
import { assert, test } from 'vitest'
test('assert.isAtLeast', () => {
assert.isAtLeast(5, 2, '5 is greater or equal to 2')
assert.isAtLeast(3, 3, '3 is greater or equal to 3')
})
```
## isBelow
* **Type:** `(valueToCheck: number, valueToBeBelow: number, message?: string) => void`
Asserts `valueToCheck` is strictly less than (<) `valueToBeBelow`.
```ts
import { assert, test } from 'vitest'
test('assert.isBelow', () => {
assert.isBelow(3, 6, '3 is strictly less than 6')
})
```
## isAtMost
* **Type:** `(valueToCheck: number, valueToBeAtMost: number, message?: string) => void`
Asserts `valueToCheck` is less than or equal to (<=) `valueToBeAtMost`.
```ts
import { assert, test } from 'vitest'
test('assert.isAtMost', () => {
assert.isAtMost(3, 6, '3 is less than or equal to 6')
assert.isAtMost(4, 4, '4 is less than or equal to 4')
})
```
## isTrue
* **Type:** `(value: T, message?: string) => asserts value is true`
Asserts that `value` is true.
```ts
import { assert, test } from 'vitest'
const testPassed = true
test('assert.isTrue', () => {
assert.isTrue(testPassed)
})
```
## isNotTrue
* **Type:** `(value: T, message?: string) => asserts value is Exclude`
Asserts that `value` is not true.
```ts
import { assert, test } from 'vitest'
const testPassed = 'ok'
test('assert.isNotTrue', () => {
assert.isNotTrue(testPassed)
})
```
## isFalse
* **Type:** `(value: T, message?: string) => asserts value is false`
Asserts that `value` is false.
```ts
import { assert, test } from 'vitest'
const testPassed = false
test('assert.isFalse', () => {
assert.isFalse(testPassed)
})
```
## isNotFalse
* **Type:** `(value: T, message?: string) => asserts value is Exclude`
Asserts that `value` is not false.
```ts
import { assert, test } from 'vitest'
const testPassed = 'no'
test('assert.isNotFalse', () => {
assert.isNotFalse(testPassed)
})
```
## isNull
* **Type:** `(value: T, message?: string) => asserts value is null`
Asserts that `value` is null.
```ts
import { assert, test } from 'vitest'
const error = null
test('assert.isNull', () => {
assert.isNull(error, 'error is null')
})
```
## isNotNull
* **Type:** `(value: T, message?: string) => asserts value is Exclude`
Asserts that `value` is not null.
```ts
import { assert, test } from 'vitest'
const error = { message: 'error was occurred' }
test('assert.isNotNull', () => {
assert.isNotNull(error, 'error is not null but object')
})
```
## isNaN
* **Type:** `(value: T, message?: string) => void`
Asserts that `value` is NaN.
```ts
import { assert, test } from 'vitest'
const calculation = 1 * 'vitest'
test('assert.isNaN', () => {
assert.isNaN(calculation, '1 * "vitest" is NaN')
})
```
## isNotNaN
* **Type:** `(value: T, message?: string) => void`
Asserts that `value` is not NaN.
```ts
import { assert, test } from 'vitest'
const calculation = 1 * 2
test('assert.isNotNaN', () => {
assert.isNotNaN(calculation, '1 * 2 is Not NaN but 2')
})
```
## exists
* **Type:** `(value: T, message?: string) => asserts value is NonNullable`
Asserts that `value` is neither null nor undefined.
```ts
import { assert, test } from 'vitest'
const name = 'foo'
test('assert.exists', () => {
assert.exists(name, 'foo is neither null nor undefined')
})
```
## notExists
* **Type:** `(value: T, message?: string) => asserts value is null | undefined`
Asserts that `value` is either null nor undefined.
```ts
import { assert, test } from 'vitest'
const foo = null
const bar = undefined
test('assert.notExists', () => {
assert.notExists(foo, 'foo is null so not exist')
assert.notExists(bar, 'bar is undefined so not exist')
})
```
## isUndefined
* **Type:** `(value: T, message?: string) => asserts value is undefined`
Asserts that `value` is undefined.
```ts
import { assert, test } from 'vitest'
const name = undefined
test('assert.isUndefined', () => {
assert.isUndefined(name, 'name is undefined')
})
```
## isDefined
* **Type:** `(value: T, message?: string) => asserts value is Exclude`
Asserts that `value` is not undefined.
```ts
import { assert, test } from 'vitest'
const name = 'foo'
test('assert.isDefined', () => {
assert.isDefined(name, 'name is not undefined')
})
```
## isFunction
* **Type:** `(value: T, message?: string) => void`
* **Alias:** `isCallable`
Asserts that `value` is a function.
```ts
import { assert, test } from 'vitest'
function name() { return 'foo' };
test('assert.isFunction', () => {
assert.isFunction(name, 'name is function')
})
```
## isNotFunction
* **Type:** `(value: T, message?: string) => void`
* **Alias:** `isNotCallable`
Asserts that `value` is not a function.
```ts
import { assert, test } from 'vitest'
const name = 'foo'
test('assert.isNotFunction', () => {
assert.isNotFunction(name, 'name is not function but string')
})
```
## isObject
* **Type:** `(value: T, message?: string) => void`
Asserts that `value` is an object of type Object (as revealed by Object.prototype.toString). The assertion does not match subclassed objects.
```ts
import { assert, test } from 'vitest'
const someThing = { color: 'red', shape: 'circle' }
test('assert.isObject', () => {
assert.isObject(someThing, 'someThing is object')
})
```
## isNotObject
* **Type:** `(value: T, message?: string) => void`
Asserts that `value` is not an object of type Object (as revealed by Object.prototype.toString). The assertion does not match subclassed objects.
```ts
import { assert, test } from 'vitest'
const someThing = 'redCircle'
test('assert.isNotObject', () => {
assert.isNotObject(someThing, 'someThing is not object but string')
})
```
## isArray
* **Type:** `(value: T, message?: string) => void`
Asserts that `value` is an array.
```ts
import { assert, test } from 'vitest'
const color = ['red', 'green', 'yellow']
test('assert.isArray', () => {
assert.isArray(color, 'color is array')
})
```
## isNotArray
* **Type:** `(value: T, message?: string) => void`
Asserts that `value` is not an array.
```ts
import { assert, test } from 'vitest'
const color = 'red'
test('assert.isNotArray', () => {
assert.isNotArray(color, 'color is not array but string')
})
```
## isString
* **Type:** `(value: T, message?: string) => void`
Asserts that `value` is a string.
```ts
import { assert, test } from 'vitest'
const color = 'red'
test('assert.isString', () => {
assert.isString(color, 'color is string')
})
```
## isNotString
* **Type:** `(value: T, message?: string) => void`
Asserts that `value` is not a string.
```ts
import { assert, test } from 'vitest'
const color = ['red', 'green', 'yellow']
test('assert.isNotString', () => {
assert.isNotString(color, 'color is not string but array')
})
```
## isNumber
* **Type:** `(value: T, message?: string) => void`
Asserts that `value` is a number.
```ts
import { assert, test } from 'vitest'
const colors = 3
test('assert.isNumber', () => {
assert.isNumber(colors, 'colors is number')
})
```
## isNotNumber
* **Type:** `(value: T, message?: string) => void`
Asserts that `value` is not a number.
```ts
import { assert, test } from 'vitest'
const colors = '3 colors'
test('assert.isNotNumber', () => {
assert.isNotNumber(colors, 'colors is not number but strings')
})
```
## isFinite
* **Type:** `(value: T, message?: string) => void`
Asserts that `value` is a finite number (not NaN, Infinity).
```ts
import { assert, test } from 'vitest'
const colors = 3
test('assert.isFinite', () => {
assert.isFinite(colors, 'colors is number not NaN or Infinity')
})
```
## isBoolean
* **Type:** `(value: T, message?: string) => void`
Asserts that `value` is a boolean.
```ts
import { assert, test } from 'vitest'
const isReady = true
test('assert.isBoolean', () => {
assert.isBoolean(isReady, 'isReady is a boolean')
})
```
## isNotBoolean
* **Type:** `(value: T, message?: string) => void`
Asserts that `value` is not a boolean.
```ts
import { assert, test } from 'vitest'
const isReady = 'sure'
test('assert.isBoolean', () => {
assert.isBoolean(isReady, 'isReady is not a boolean but string')
})
```
## typeOf
* **Type:** `(value: T, name: string, message?: string) => void`
Asserts that `value`’s type is `name`, as determined by Object.prototype.toString.
```ts
import { assert, test } from 'vitest'
test('assert.typeOf', () => {
assert.typeOf({ color: 'red' }, 'object', 'we have an object')
assert.typeOf(['red', 'green'], 'array', 'we have an array')
assert.typeOf('red', 'string', 'we have a string')
assert.typeOf(/red/, 'regexp', 'we have a regular expression')
assert.typeOf(null, 'null', 'we have a null')
assert.typeOf(undefined, 'undefined', 'we have an undefined')
})
```
## notTypeOf
* **Type:** `(value: T, name: string, message?: string) => void`
Asserts that `value`’s type is not `name`, as determined by Object.prototype.toString.
```ts
import { assert, test } from 'vitest'
test('assert.notTypeOf', () => {
assert.notTypeOf('red', 'number', '"red" is not a number')
})
```
## instanceOf
* **Type:** `(value: T, constructor: Function, message?: string) => asserts value is T`
Asserts that `value` is an instance of `constructor`.
```ts
import { assert, test } from 'vitest'
function Person(name) { this.name = name }
const foo = new Person('foo')
class Tea {
constructor(name) {
this.name = name
}
}
const coffee = new Tea('coffee')
test('assert.instanceOf', () => {
assert.instanceOf(foo, Person, 'foo is an instance of Person')
assert.instanceOf(coffee, Tea, 'coffee is an instance of Tea')
})
```
## notInstanceOf
* **Type:** `(value: T, constructor: Function, message?: string) => asserts value is Exclude`
Asserts that `value` is not an instance of `constructor`.
```ts
import { assert, test } from 'vitest'
function Person(name) { this.name = name }
const foo = new Person('foo')
class Tea {
constructor(name) {
this.name = name
}
}
const coffee = new Tea('coffee')
test('assert.instanceOf', () => {
assert.instanceOf(foo, Tea, 'foo is not an instance of Tea')
})
```
## include
* **Type:**
* `(haystack: string, needle: string, message?: string) => void`
* `(haystack: readonly T[] | ReadonlySet | ReadonlyMap, needle: T, message?: string) => void`
* `(haystack: WeakSet, needle: T, message?: string) => void`
* `(haystack: T, needle: Partial, message?: string) => void`
Asserts that `haystack` includes `needle`. Can be used to assert the inclusion of a value in an array, a substring in a string, or a subset of properties in an object.
```ts
import { assert, test } from 'vitest'
test('assert.include', () => {
assert.include([1, 2, 3], 2, 'array contains value')
assert.include('foobar', 'foo', 'string contains substring')
assert.include({ foo: 'bar', hello: 'universe' }, { foo: 'bar' }, 'object contains property')
})
```
## notInclude
* **Type:**
* `(haystack: string, needle: string, message?: string) => void`
* `(haystack: readonly T[] | ReadonlySet | ReadonlyMap, needle: T, message?: string) => void`
* `(haystack: WeakSet, needle: T, message?: string) => void`
* `(haystack: T, needle: Partial, message?: string) => void`
Asserts that `haystack` does not include `needle`. It can be used to assert the absence of a value in an array, a substring in a string, or a subset of properties in an object.
```ts
import { assert, test } from 'vitest'
test('assert.notInclude', () => {
assert.notInclude([1, 2, 3], 4, 'array doesn\'t contain 4')
assert.notInclude('foobar', 'baz', 'foobar doesn\'t contain baz')
assert.notInclude({ foo: 'bar', hello: 'universe' }, { foo: 'baz' }, 'object doesn\'t contain property')
})
```
## deepInclude
* **Type:**
* `(haystack: string, needle: string, message?: string) => void`
* `(haystack: readonly T[] | ReadonlySet | ReadonlyMap, needle: T, message?: string) => void`
* `(haystack: T, needle: T extends WeakSet ? never : Partial, message?: string) => void`
Asserts that `haystack` includes `needle`. Can be used to assert the inclusion of a value in an array or a subset of properties in an object. Deep equality is used.
```ts
import { assert, test } from 'vitest'
const obj1 = { a: 1 }
const obj2 = { b: 2 }
test('assert.deepInclude', () => {
assert.deepInclude([obj1, obj2], { a: 1 })
assert.deepInclude({ foo: obj1, bar: obj2 }, { foo: { a: 1 } })
})
```
## notDeepInclude
* **Type:**
* `(haystack: string, needle: string, message?: string) => void`
* `(haystack: readonly T[] | ReadonlySet | ReadonlyMap, needle: T, message?: string) => void`
* `(haystack: T, needle: T extends WeakSet ? never : Partial, message?: string) => void`
Asserts that `haystack` does not include `needle`. It can be used to assert the absence of a value in an array or a subset of properties in an object. Deep equality is used.
```ts
import { assert, test } from 'vitest'
const obj1 = { a: 1 }
const obj2 = { b: 2 }
test('assert.notDeepInclude', () => {
assert.notDeepInclude([obj1, obj2], { a: 10 })
assert.notDeepInclude({ foo: obj1, bar: obj2 }, { foo: { a: 10 } })
})
```
## nestedInclude
* **Type:** `(haystack: any, needle: any, message?: string) => void`
Asserts that `haystack` includes `needle`. Can be used to assert the inclusion of a subset of properties in an object. Enables the use of dot- and bracket-notation for referencing nested properties. ‘\[]’ and ‘.’ in property names can be escaped using double backslashes.
```ts
import { assert, test } from 'vitest'
test('assert.nestedInclude', () => {
assert.nestedInclude({ '.a': { b: 'x' } }, { '\\.a.[b]': 'x' })
assert.nestedInclude({ a: { '[b]': 'x' } }, { 'a.\\[b\\]': 'x' })
})
```
## notNestedInclude
* **Type:** `(haystack: any, needle: any, message?: string) => void`
Asserts that `haystack` does not include `needle`. Can be used to assert the inclusion of a subset of properties in an object. Enables the use of dot- and bracket-notation for referencing nested properties. ‘\[]’ and ‘.’ in property names can be escaped using double backslashes.
```ts
import { assert, test } from 'vitest'
test('assert.nestedInclude', () => {
assert.notNestedInclude({ '.a': { b: 'x' } }, { '\\.a.b': 'y' })
assert.notNestedInclude({ a: { '[b]': 'x' } }, { 'a.\\[b\\]': 'y' })
})
```
## deepNestedInclude
* **Type:** `(haystack: any, needle: any, message?: string) => void`
Asserts that `haystack` includes `needle`. Can be used to assert the inclusion of a subset of properties in an object while checking for deep equality. Enables the use of dot- and bracket-notation for referencing nested properties. ‘\[]’ and ‘.’ in property names can be escaped using double backslashes.
```ts
import { assert, test } from 'vitest'
test('assert.deepNestedInclude', () => {
assert.deepNestedInclude({ a: { b: [{ x: 1 }] } }, { 'a.b[0]': { x: 1 } })
assert.deepNestedInclude({ '.a': { '[b]': { x: 1 } } }, { '\\.a.\\[b\\]': { x: 1 } })
})
```
## notDeepNestedInclude
* **Type:** `(haystack: any, needle: any, message?: string) => void`
Asserts that `haystack` not includes `needle`. Can be used to assert the absence of a subset of properties in an object while checking for deep equality. Enables the use of dot- and bracket-notation for referencing nested properties. ‘\[]’ and ‘.’ in property names can be escaped using double backslashes.
```ts
import { assert, test } from 'vitest'
test('assert.notDeepNestedInclude', () => {
assert.notDeepNestedInclude({ a: { b: [{ x: 1 }] } }, { 'a.b[0]': { y: 1 } })
assert.notDeepNestedInclude({ '.a': { '[b]': { x: 1 } } }, { '\\.a.\\[b\\]': { y: 2 } })
})
```
## ownInclude
* **Type:** `(haystack: any, needle: any, message?: string) => void`
Asserts that `haystack` includes `needle`. Can be used to assert the inclusion of a subset of properties in an object while ignoring inherited properties.
```ts
import { assert, test } from 'vitest'
test('assert.ownInclude', () => {
assert.ownInclude({ a: 1 }, { a: 1 })
})
```
## notOwnInclude
* **Type:** `(haystack: any, needle: any, message?: string) => void`
Asserts that `haystack` includes `needle`. Can be used to assert the absence of a subset of properties in an object while ignoring inherited properties.
```ts
import { assert, test } from 'vitest'
const obj1 = {
b: 2
}
const obj2 = object.create(obj1)
obj2.a = 1
test('assert.notOwnInclude', () => {
assert.notOwnInclude(obj2, { b: 2 })
})
```
## deepOwnInclude
* **Type:** `(haystack: any, needle: any, message?: string) => void`
Asserts that `haystack` includes `needle`. Can be used to assert the inclusion of a subset of properties in an object while ignoring inherited properties and checking for deep equality.
```ts
import { assert, test } from 'vitest'
test('assert.deepOwnInclude', () => {
assert.deepOwnInclude({ a: { b: 2 } }, { a: { b: 2 } })
})
```
## notDeepOwnInclude
* **Type:** `(haystack: any, needle: any, message?: string) => void`
Asserts that `haystack` not includes `needle`. Can be used to assert the absence of a subset of properties in an object while ignoring inherited properties and checking for deep equality.
```ts
import { assert, test } from 'vitest'
test('assert.notDeepOwnInclude', () => {
assert.notDeepOwnInclude({ a: { b: 2 } }, { a: { c: 3 } })
})
```
## match
* **Type:** `(value: string, regexp: RegExp, message?: string) => void`
Asserts that `value` matches the regular expression `regexp`.
```ts
import { assert, test } from 'vitest'
test('assert.match', () => {
assert.match('foobar', /^foo/, 'regexp matches')
})
```
## notMatch
* **Type:** `(value: string, regexp: RegExp, message?: string) => void`
Asserts that `value` does not matches the regular expression `regexp`.
```ts
import { assert, test } from 'vitest'
test('assert.notMatch', () => {
assert.notMatch('foobar', /^foo/, 'regexp does not match')
})
```
## property
* **Type:** `(object: T, property: string, message?: string) => void`
Asserts that `object` has a direct or inherited property named by `property`
```ts
import { assert, test } from 'vitest'
test('assert.property', () => {
assert.property({ tea: { green: 'matcha' } }, 'tea')
assert.property({ tea: { green: 'matcha' } }, 'toString')
})
```
## notProperty
* **Type:** `(object: T, property: string, message?: string) => void`
Asserts that `object` does not have a direct or inherited property named by `property`
```ts
import { assert, test } from 'vitest'
test('assert.notProperty', () => {
assert.notProperty({ tea: { green: 'matcha' } }, 'coffee')
})
```
## propertyVal
* **Type:** `(object: T, property: string, value: V, message?: string) => void`
Asserts that `object` has a direct or inherited property named by `property` with a value given by `value`. Uses a strict equality check (===).
```ts
import { assert, test } from 'vitest'
test('assert.notPropertyVal', () => {
assert.propertyVal({ tea: 'is good' }, 'tea', 'is good')
})
```
## notPropertyVal
* **Type:** `(object: T, property: string, value: V, message?: string) => void`
Asserts that `object` does not have a direct or inherited property named by `property` with a value given by `value`. Uses a strict equality check (===).
```ts
import { assert, test } from 'vitest'
test('assert.notPropertyVal', () => {
assert.notPropertyVal({ tea: 'is good' }, 'tea', 'is bad')
assert.notPropertyVal({ tea: 'is good' }, 'coffee', 'is good')
})
```
## deepPropertyVal
* **Type:** `(object: T, property: string, value: V, message?: string) => void`
Asserts that `object` has a direct or inherited property named by `property` with a value given by `value`. Uses a deep equality check.
```ts
import { assert, test } from 'vitest'
test('assert.deepPropertyVal', () => {
assert.deepPropertyVal({ tea: { green: 'matcha' } }, 'tea', { green: 'matcha' })
})
```
## notDeepPropertyVal
* **Type:** `(object: T, property: string, value: V, message?: string) => void`
Asserts that `object` does not have a direct or inherited property named by `property` with a value given by `value`. Uses a deep equality check.
```ts
import { assert, test } from 'vitest'
test('assert.deepPropertyVal', () => {
assert.notDeepPropertyVal({ tea: { green: 'matcha' } }, 'tea', { black: 'matcha' })
assert.notDeepPropertyVal({ tea: { green: 'matcha' } }, 'tea', { green: 'oolong' })
assert.notDeepPropertyVal({ tea: { green: 'matcha' } }, 'coffee', { green: 'matcha' })
})
```
## nestedProperty
* **Type:** `(object: T, property: string, message?: string) => void`
Asserts that `object` has a direct or inherited property named by `property`, which can be a string using dot- and bracket-notation for nested reference.
```ts
import { assert, test } from 'vitest'
test('assert.deepPropertyVal', () => {
assert.nestedProperty({ tea: { green: 'matcha' } }, 'tea.green')
})
```
## notNestedProperty
* **Type:** `(object: T, property: string, message?: string) => void`
Asserts that `object` does not have a direct or inherited property named by `property`, which can be a string using dot- and bracket-notation for nested reference.
```ts
import { assert, test } from 'vitest'
test('assert.deepPropertyVal', () => {
assert.notNestedProperty({ tea: { green: 'matcha' } }, 'tea.oolong')
})
```
## nestedPropertyVal
* **Type:** `(object: T, property: string, value: any, message?: string) => void`
Asserts that `object` has a property named by `property` with value given by `value`. `property` can use dot- and bracket-notation for nested reference. Uses a strict equality check (===).
```ts
import { assert, test } from 'vitest'
test('assert.nestedPropertyVal', () => {
assert.nestedPropertyVal({ tea: { green: 'matcha' } }, 'tea.green', 'matcha')
})
```
## notNestedPropertyVal
* **Type:** `(object: T, property: string, value: any, message?: string) => void`
Asserts that `object` does not have a property named by `property` with value given by `value`. `property` can use dot- and bracket-notation for nested reference. Uses a strict equality check (===).
```ts
import { assert, test } from 'vitest'
test('assert.notNestedPropertyVal', () => {
assert.notNestedPropertyVal({ tea: { green: 'matcha' } }, 'tea.green', 'konacha')
assert.notNestedPropertyVal({ tea: { green: 'matcha' } }, 'coffee.green', 'matcha')
})
```
## deepNestedPropertyVal
* **Type:** `(object: T, property: string, value: any, message?: string) => void`
Asserts that `object` has a property named by `property` with a value given by `value`. `property` can use dot- and bracket-notation for nested reference. Uses a deep equality check (===).
```ts
import { assert, test } from 'vitest'
test('assert.notNestedPropertyVal', () => {
assert.notNestedPropertyVal({ tea: { green: 'matcha' } }, 'tea.green', 'konacha')
assert.notNestedPropertyVal({ tea: { green: 'matcha' } }, 'coffee.green', 'matcha')
})
```
## notDeepNestedPropertyVal
* **Type:** `(object: T, property: string, value: any, message?: string) => void`
Asserts that `object` does not have a property named by `property` with value given by `value`. `property` can use dot- and bracket-notation for nested reference. Uses a deep equality check.
```ts
import { assert, test } from 'vitest'
test('assert.notDeepNestedPropertyVal', () => {
assert.notDeepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.green', { oolong: 'yum' })
assert.notDeepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.green', { matcha: 'yuck' })
assert.notDeepNestedPropertyVal({ tea: { green: { matcha: 'yum' } } }, 'tea.black', { matcha: 'yum' })
})
```
## lengthOf
* **Type:** `(object: T, length: number, message?: string) => void`
Asserts that `object` has a `length` or `size` with the expected value.
```ts
import { assert, test } from 'vitest'
test('assert.lengthOf', () => {
assert.lengthOf([1, 2, 3], 3, 'array has length of 3')
assert.lengthOf('foobar', 6, 'string has length of 6')
assert.lengthOf(new Set([1, 2, 3]), 3, 'set has size of 3')
assert.lengthOf(new Map([['a', 1], ['b', 2], ['c', 3]]), 3, 'map has size of 3')
})
```
## hasAnyKeys
* **Type:** `(object: T, keys: Array
```
```javascript
await expect.element(getByTestId('img-alt')).toHaveAccessibleName('Test alt')
await expect.element(getByTestId('img-empty-alt')).not.toHaveAccessibleName()
await expect.element(getByTestId('svg-title')).toHaveAccessibleName('Test title')
await expect.element(getByTestId('button-img-alt')).toHaveAccessibleName()
await expect.element(getByTestId('img-paragraph')).not.toHaveAccessibleName()
await expect.element(getByTestId('svg-button')).toHaveAccessibleName()
await expect.element(getByTestId('svg-without-title')).not.toHaveAccessibleName()
await expect.element(getByTestId('input-title')).toHaveAccessibleName()
```
## toHaveAttribute
```ts
function toHaveAttribute(attribute: string, value?: unknown): Promise
```
This allows you to check whether the given element has an attribute or not. You
can also optionally check that the attribute has a specific expected value or
partial match using [`expect.stringContaining`](/api/expect#expect-stringcontaining) or [`expect.stringMatching`](/api/expect#expect-stringmatching).
```html
```
```ts
const button = getByTestId('ok-button')
await expect.element(button).toHaveAttribute('disabled')
await expect.element(button).toHaveAttribute('type', 'submit')
await expect.element(button).not.toHaveAttribute('type', 'button')
await expect.element(button).toHaveAttribute(
'type',
expect.stringContaining('sub')
)
await expect.element(button).toHaveAttribute(
'type',
expect.not.stringContaining('but')
)
```
## toHaveClass
```ts
function toHaveClass(...classNames: string[], options?: { exact: boolean }): Promise
function toHaveClass(...classNames: (string | RegExp)[]): Promise
```
This allows you to check whether the given element has certain classes within
its `class` attribute. You must provide at least one class, unless you are
asserting that an element does not have any classes.
The list of class names may include strings and regular expressions. Regular
expressions are matched against each individual class in the target element, and
it is NOT matched against its full `class` attribute value as whole.
::: warning
Note that you cannot use `exact: true` option when only regular expressions are provided.
:::
```html
```
```ts
const deleteButton = getByTestId('delete-button')
const noClasses = getByTestId('no-classes')
await expect.element(deleteButton).toHaveClass('extra')
await expect.element(deleteButton).toHaveClass('btn-danger btn')
await expect.element(deleteButton).toHaveClass(/danger/, 'btn')
await expect.element(deleteButton).toHaveClass('btn-danger', 'btn')
await expect.element(deleteButton).not.toHaveClass('btn-link')
await expect.element(deleteButton).not.toHaveClass(/link/)
// ⚠️ regexp matches against individual classes, not the whole classList
await expect.element(deleteButton).not.toHaveClass(/btn extra/)
// the element has EXACTLY a set of classes (in any order)
await expect.element(deleteButton).toHaveClass('btn-danger extra btn', {
exact: true
})
// if it has more than expected it is going to fail
await expect.element(deleteButton).not.toHaveClass('btn-danger extra', {
exact: true
})
await expect.element(noClasses).not.toHaveClass()
```
## toHaveFocus
```ts
function toHaveFocus(): Promise
```
This allows you to assert whether an element has focus or not.
```html
```
```ts
const input = page.getByTestId('element-to-focus')
input.element().focus()
await expect.element(input).toHaveFocus()
input.element().blur()
await expect.element(input).not.toHaveFocus()
```
## toHaveFormValues
```ts
function toHaveFormValues(expectedValues: Record): Promise
```
This allows you to check if a form or fieldset contains form controls for each given name, and having the specified value.
::: tip
It is important to stress that this matcher can only be invoked on a [form](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement) or a [fieldset](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFieldSetElement) element.
This allows it to take advantage of the [`.elements`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLFormElement/elements) property in `form` and `fieldset` to reliably fetch all form controls within them.
This also avoids the possibility that users provide a container that contains more than one `form`, thereby intermixing form controls that are not related, and could even conflict with one another.
:::
This matcher abstracts away the particularities with which a form control value
is obtained depending on the type of form control. For instance, ``
elements have a `value` attribute, but `