Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions docs/api/browser/locators.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,29 @@ The locator API uses a fork of [Playwright's locators](https://playwright.dev/do
This page covers API usage. To better understand locators and their usage, read [Playwright's "Locators" documentation](https://playwright.dev/docs/locators).
:::

::: tip Difference from `testing-library`
Vitest's `page.getBy*` methods return a locator object, not a DOM element. This makes locator queries composable and allows Vitest to retry interactions and assertions when needed.

Compared to testing-library queries:

- Use locator chaining (`.getBy*`, `.filter`, `.nth`) instead of `within(...)`.
- Keep locators around and interact with them later (`await locator.click()`), instead of resolving elements up front.
- Single-element escape hatches like `.element()` and `.query()` are strict and throw if multiple elements match.

```ts
import { expect } from 'vitest'
import { page } from 'vitest/browser'

const deleteButton = page
.getByRole('row')
.filter({ hasText: 'Vitest' })
.getByRole('button', { name: /delete/i })

await deleteButton.click()
await expect.element(deleteButton).toBeEnabled()
```
:::

## getByRole

```ts
Expand Down
44 changes: 44 additions & 0 deletions docs/guide/common-errors.md
Original file line number Diff line number Diff line change
Expand Up @@ -121,3 +121,47 @@ export default defineConfig({
vitest --pool=forks
```
:::

## Unhandled Promise Rejection

This error happens when a Promise rejects but no `.catch()` handler or `await` is attached to it before the microtask queue flushes. This behavior comes from JavaScript itself and is not specific to Vitest. Learn more in the [Node.js documentation](https://nodejs.org/api/process.html#event-unhandledrejection).

A common cause is calling an async function without `await`ing it:

```ts
async function fetchUser(id) {
const res = await fetch(`/api/users/${id}`)
if (!res.ok) {
throw new Error(`User ${id} not found`) // [!code highlight]
}
return res.json()
}

test('fetches user', async () => {
fetchUser(123) // [!code error]
})
```

Because `fetchUser()` is not `await`ed, its rejection has no handler and Vitest reports:

```
Unhandled Rejection: Error: User 123 not found
```

### Fix

`await` the promise so Vitest can catch the error:

```ts
test('fetches user', async () => {
await fetchUser(123) // [!code ++]
})
```

If you expect the call to throw, use [`expect().rejects`](/api/expect#rejects):

```ts
test('rejects for missing user', async () => {
await expect(fetchUser(123)).rejects.toThrow('User 123 not found')
})
```
32 changes: 20 additions & 12 deletions docs/guide/recipes.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,15 +15,19 @@ export default defineConfig({
test: {
projects: [
{
// Non-isolated unit tests
name: 'Unit tests',
isolate: false,
exclude: ['**.integration.test.ts'],
test: {
// Non-isolated unit tests
name: 'Unit tests',
isolate: false,
exclude: ['**.integration.test.ts'],
},
},
{
// Isolated integration tests
name: 'Integration tests',
include: ['**.integration.test.ts'],
test: {
// Isolated integration tests
name: 'Integration tests',
include: ['**.integration.test.ts'],
},
},
],
},
Expand All @@ -41,13 +45,17 @@ export default defineConfig({
test: {
projects: [
{
name: 'Parallel',
exclude: ['**.sequential.test.ts'],
test: {
name: 'Parallel',
exclude: ['**.sequential.test.ts'],
},
},
{
name: 'Sequential',
include: ['**.sequential.test.ts'],
fileParallelism: false,
test: {
name: 'Sequential',
include: ['**.sequential.test.ts'],
fileParallelism: false,
},
},
],
},
Expand Down
6 changes: 6 additions & 0 deletions packages/ui/node/reporter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,12 @@ export default class HTMLReporter implements Reporter {
if (this.ctx.config.coverage.enabled && this.ctx.config.coverage.htmlDir) {
const coverageHtmlDir = this.ctx.config.coverage.htmlDir
const destCoverageDir = resolve(this.reporterDir, 'coverage')
if (coverageHtmlDir === destCoverageDir) {
// skip and preserve already generated coverage report.
// this can happen when users configures `outputFile`
// next to `coverage.reportsDirectory`.
return
}
await fs.rm(destCoverageDir, { recursive: true, force: true })
await fs.mkdir(destCoverageDir, { recursive: true })
await fs.cp(coverageHtmlDir, destCoverageDir, { recursive: true })
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ export function startVitestModuleRunner(options: ContextModuleRunnerOptions): Vi

// if module is invalidated, the worker will be recreated,
// so cached is always true in a single worker
if (options?.cached) {
if (!isImportActual && options?.cached) {
return { cache: true }
}

Expand Down
8 changes: 8 additions & 0 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions test/cli/deps/dep-simple/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export default 'test-dep-simple'
6 changes: 6 additions & 0 deletions test/cli/deps/dep-simple/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"name": "test-dep-simple",
"type": "module",
"private": true,
"exports": "./index.js"
}
1 change: 1 addition & 0 deletions test/cli/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"obug": "^2.1.1",
"playwright": "catalog:",
"test-dep-invalid": "link:./deps/dep-invalid",
"test-dep-simple": "file:./deps/dep-simple",
"tinyspy": "catalog:",
"typescript": "catalog:",
"unplugin-swc": "^1.5.9",
Expand Down
149 changes: 149 additions & 0 deletions test/cli/test/mocking.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -391,3 +391,152 @@ test('mock works without loading original', () => {
}
`)
})

test.for([
'node',
'playwright',
'webdriverio',
])('repeating mock, importActual, and resetModules (%s)', async (mode) => {
const { stderr, errorTree } = await runInlineTests({
// external
'./external.test.ts': `
import { expect, test, vi } from "vitest"

test("external", async () => {
vi.doMock(import("test-dep-simple"), async (importActual) => {
const lib = await importActual();
return lib;
})
const lib1: any = await import("test-dep-simple")
expect(lib1.default).toBe("test-dep-simple")

vi.resetModules();
vi.doMock(import("test-dep-simple"), async (importActual) => {
const lib = await importActual();
return lib;
})
const lib2: any = await import("test-dep-simple")
expect(lib2.default).toBe("test-dep-simple")
expect.soft(lib1 !== lib2).toBe(true)

vi.resetModules();
vi.doMock(import("test-dep-simple"), async () => ({ mocked: true }));
const lib3 = await import("test-dep-simple");
expect(lib3).toMatchObject({ mocked: true })

const lib4 = await vi.importActual("test-dep-simple");
expect(lib4.default).toBe("test-dep-simple")
const lib5 = await vi.importActual("test-dep-simple");
expect(lib4).toBe(lib5)
});
`,
// builtin module
'./builtin.test.ts': `
import { expect, test, vi } from "vitest"

test("builtin", async () => {
vi.doMock(import("node:path"), async (importActual) => {
const lib = await importActual();
return lib;
})
const lib1: any = await import("node:path")
expect(lib1).toHaveProperty('join')

vi.resetModules();
vi.doMock(import("node:path"), async (importActual) => {
const lib = await importActual();
return lib;
})
const lib2: any = await import("node:path")
expect(lib2).toHaveProperty('join')
expect.soft(lib1 !== lib2).toBe(true)

vi.resetModules();
vi.doMock(import("node:path"), async () => ({ mocked: true }));
const lib3 = await import("node:path");
expect(lib3).toMatchObject({ mocked: true })

const lib4 = await vi.importActual("node:path");
expect(lib4).toHaveProperty('join')
const lib5 = await vi.importActual("node:path");
expect(lib4).toBe(lib5)
});
`,
// local module
'./local.test.ts': `
import { expect, test, vi } from "vitest"

test("local", async () => {
vi.doMock(import("./local.js"), async (importActual) => {
const lib = await importActual();
return lib;
})
const lib1: any = await import("./local.js")
expect(lib1).toHaveProperty('local')

vi.resetModules();
vi.doMock(import("./local.js"), async (importActual) => {
const lib = await importActual();
return lib;
})
const lib2: any = await import("./local.js")
expect(lib2).toHaveProperty('local')
expect.soft(lib1 !== lib2).toBe(true)

vi.resetModules();
vi.doMock(import("./local.js"), async () => ({ mocked: true }));
const lib3 = await import("./local.js");
expect(lib3).toMatchObject({ mocked: true })

const lib4 = await vi.importActual("./local.js");
expect(lib4).toHaveProperty('local')
const lib5 = await vi.importActual("./local.js");
expect(lib4).toBe(lib5)
});
`,
'./local.js': `export const local = 'local'`,
}, modeToConfig(mode))

if (mode === 'webdriverio' || mode === 'playwright') {
// browser mode doesn't support resetModules nor node builtin
expect(errorTree()).toMatchInlineSnapshot(`
{
"builtin.test.ts": {
"builtin": [
"Cannot convert a Symbol value to a string",
],
},
"external.test.ts": {
"external": [
"expected false to be true // Object.is equality",
"expected { default: 'test-dep-simple', …(1) } to match object { mocked: true }
(1 matching property omitted from actual)",
],
},
"local.test.ts": {
"local": [
"expected false to be true // Object.is equality",
"expected { local: 'local', …(1) } to match object { mocked: true }
(1 matching property omitted from actual)",
],
},
}
`)
return
}

expect(stderr).toMatchInlineSnapshot(`""`)
expect(errorTree()).toMatchInlineSnapshot(`
{
"builtin.test.ts": {
"builtin": "passed",
},
"external.test.ts": {
"external": "passed",
},
"local.test.ts": {
"local": "passed",
},
}
`)
})
Loading
Loading