Skip to content

Commit

Permalink
Merge branch 'main' into fix-eco-ci-6
Browse files Browse the repository at this point in the history
  • Loading branch information
hi-ogawa committed Nov 14, 2024
2 parents f5fbd55 + b915aa6 commit ed8a96e
Show file tree
Hide file tree
Showing 114 changed files with 1,998 additions and 541 deletions.
68 changes: 67 additions & 1 deletion docs/api/expect.md
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ test('element exists', async () => {
```

::: warning
`expect.poll` makes every assertion asynchronous, so do not forget to await it otherwise you might get unhandled promise rejections.
`expect.poll` makes every assertion asynchronous, so you need to await it. Since Vitest 2.2, if you forget to await it, the test will fail with a warning to do so.

`expect.poll` doesn't work with several matchers:

Expand Down Expand Up @@ -876,6 +876,68 @@ test('spy function', () => {
})
```

## toHaveBeenCalledBefore <Version>2.2.0</Version> {#tohavebeencalledbefore}

- **Type**: `(mock: MockInstance, failIfNoFirstInvocation?: boolean) => Awaitable<void>`

This assertion checks if a `Mock` was called before another `Mock`.

```ts
test('calls mock1 before mock2', () => {
const mock1 = vi.fn()
const mock2 = vi.fn()

mock1()
mock2()
mock1()

expect(mock1).toHaveBeenCalledBefore(mock2)
})
```

## toHaveBeenCalledAfter <Version>2.2.0</Version> {#tohavebeencalledafter}

- **Type**: `(mock: MockInstance, failIfNoFirstInvocation?: boolean) => Awaitable<void>`

This assertion checks if a `Mock` was called after another `Mock`.

```ts
test('calls mock1 after mock2', () => {
const mock1 = vi.fn()
const mock2 = vi.fn()

mock2()
mock1()
mock2()

expect(mock1).toHaveBeenCalledAfter(mock2)
})
```

## toHaveBeenCalledExactlyOnceWith <Version>2.2.0</Version> {#tohavebeencalledexactlyoncewith}

- **Type**: `(...args: any[]) => Awaitable<void>`

This assertion checks if a function was called exactly once and with certain parameters. Requires a spy function to be passed to `expect`.

```ts
import { expect, test, vi } from 'vitest'

const market = {
buy(subject: string, amount: number) {
// ...
},
}

test('spy function', () => {
const buySpy = vi.spyOn(market, 'buy')

market.buy('apples', 10)

expect(buySpy).toHaveBeenCalledExactlyOnceWith('apples', 10)
})
```

## toHaveBeenLastCalledWith

- **Type**: `(...args: any[]) => Awaitable<void>`
Expand Down Expand Up @@ -1185,6 +1247,8 @@ test('buyApples returns new stock id', async () => {

:::warning
If the assertion is not awaited, then you will have a false-positive test that will pass every time. To make sure that assertions are actually called, you may use [`expect.assertions(number)`](#expect-assertions).

Since Vitest 2.2, if a method is not awaited, Vitest will show a warning at the end of the test. In Vitest 3, the test will be marked as "failed" if the assertion is not awaited.
:::

## rejects
Expand Down Expand Up @@ -1214,6 +1278,8 @@ test('buyApples throws an error when no id provided', async () => {

:::warning
If the assertion is not awaited, then you will have a false-positive test that will pass every time. To make sure that assertions were actually called, you can use [`expect.assertions(number)`](#expect-assertions).

Since Vitest 2.2, if a method is not awaited, Vitest will show a warning at the end of the test. In Vitest 3, the test will be marked as "failed" if the assertion is not awaited.
:::

## expect.assertions
Expand Down
72 changes: 61 additions & 11 deletions docs/config/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -1089,6 +1089,18 @@ inject('wsPort') === 3000
```
:::

Since Vitest 2.2.0, you can define a custom callback function to be called when Vitest reruns tests. If the function is asynchronous, the runner will wait for it to complete before executing the tests.

```ts
import type { GlobalSetupContext } from 'vitest/node'

export default function setup({ onTestsRerun }: GlobalSetupContext) {
onTestsRerun(async () => {
await restartDb()
})
}
```

### forceRerunTriggers<NonProjectOption />

- **Type**: `string[]`
Expand Down Expand Up @@ -1887,7 +1899,7 @@ A list of paths to snapshot serializer modules for snapshot testing, useful if y

### resolveSnapshotPath<NonProjectOption />

- **Type**: `(testPath: string, snapExtension: string) => string`
- **Type**: `(testPath: string, snapExtension: string, context: { config: SerializedConfig }) => string`
- **Default**: stores snapshot files in `__snapshots__` directory

Overrides default snapshot path. For example, to store snapshots next to test files:
Expand Down Expand Up @@ -2284,22 +2296,32 @@ export default defineConfig({
### diff

- **Type:** `string`
- **CLI:** `--diff=<value>`
- **CLI:** `--diff=<path>`

`DiffOptions` object or a path to a module which exports `DiffOptions`. Useful if you want to customize diff display.

Path to a diff config that will be used to generate diff interface. Useful if you want to customize diff display.
For example, as a config object:

:::code-group
```ts [vitest.diff.ts]
import type { DiffOptions } from 'vitest'
import c from 'tinyrainbow'
```ts [vitest.config.js]
import { defineConfig } from 'vitest/config'
import c from 'picocolors'

export default {
aIndicator: c.bold('--'),
bIndicator: c.bold('++'),
omitAnnotationLines: true,
} satisfies DiffOptions
export default defineConfig({
test: {
diff: {
aIndicator: c.bold('--'),
bIndicator: c.bold('++'),
omitAnnotationLines: true,
}
}
})
```
:::

Or as a module:

:::code-group
```ts [vitest.config.js]
import { defineConfig } from 'vitest/config'

Expand All @@ -2309,12 +2331,32 @@ export default defineConfig({
}
})
```

```ts [vitest.diff.ts]
import type { DiffOptions } from 'vitest'
import c from 'picocolors'

export default {
aIndicator: c.bold('--'),
bIndicator: c.bold('++'),
omitAnnotationLines: true,
} satisfies DiffOptions
```
:::

#### diff.expand

- **Type**: `boolean`
- **Default**: `true`
- **CLI:** `--diff.expand=false`

Expand all common lines.

#### diff.truncateThreshold

- **Type**: `number`
- **Default**: `0`
- **CLI:** `--diff.truncateThreshold=<path>`

The maximum length of diff result to be displayed. Diffs above this threshold will be truncated.
Truncation won't take effect with default value 0.
Expand All @@ -2323,6 +2365,7 @@ Truncation won't take effect with default value 0.

- **Type**: `string`
- **Default**: `'... Diff result is truncated'`
- **CLI:** `--diff.truncateAnnotation=<annotation>`

Annotation that is output at the end of diff result if it's truncated.

Expand All @@ -2333,6 +2376,13 @@ Annotation that is output at the end of diff result if it's truncated.

Color of truncate annotation, default is output with no color.

#### diff.printBasicPrototype

- **Type**: `boolean`
- **Default**: `true`

Print basic prototype `Object` and `Array` in diff output

### fakeTimers

- **Type:** `FakeTimerInstallOpts`
Expand Down
2 changes: 2 additions & 0 deletions docs/guide/browser/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,8 @@ export default defineConfig({

::: info
Vitest assigns port `63315` to avoid conflicts with the development server, allowing you to run both in parallel. You can change that with the [`browser.api`](/config/#browser-api) option.

Since Vitest 2.1.5, the CLI no longer prints the Vite URL automatically. You can press "b" to print the URL when running in watch mode.
:::

If you have not used Vite before, make sure you have your framework's plugin installed and specified in the config. Some frameworks might require extra configuration to work - check their Vite related documentation to be sure.
Expand Down
2 changes: 2 additions & 0 deletions docs/guide/browser/locators.md
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,8 @@ It is recommended to use this only after the other locators don't work for your

## Methods

All methods are asynchronous and must be awaited. Since Vitest 2.2, tests will fail if a method is not awaited.

### click

```ts
Expand Down
9 changes: 7 additions & 2 deletions docs/guide/reporters.md
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ export default defineConfig({

### JSON Reporter

Outputs a report of the test results in JSON format. Can either be printed to the terminal or written to a file using the [`outputFile`](/config/#outputfile) configuration option.
Generates a report of the test results in a JSON format compatible with Jest's `--json` option. Can either be printed to the terminal or written to a file using the [`outputFile`](/config/#outputfile) configuration option.

:::code-group
```bash [CLI]
Expand Down Expand Up @@ -322,10 +322,15 @@ Example of a JSON report:
"message": "",
"name": "/root-directory/__tests__/test-file-1.test.ts"
}
]
],
"coverageMap": {}
}
```

::: info
Since Vitest 2.2, the JSON reporter includes coverage information in `coverageMap` if coverage is enabled.
:::

### HTML Reporter

Generates an HTML file to view test results through an interactive [GUI](/guide/ui). After the file has been generated, Vitest will keep a local development server running and provide a link to view the report in a browser.
Expand Down
56 changes: 54 additions & 2 deletions docs/guide/test-context.md
Original file line number Diff line number Diff line change
Expand Up @@ -176,9 +176,61 @@ const test = base.extend({
],
})

test('', () => {})
test('works correctly')
```

#### Default fixture

Since Vitest 2.2, you can provide different values in different [projects](/guide/workspace). To enable this feature, pass down `{ injected: true }` to the options. If the key is not specified in the [project configuration](/config/#provide), then the default value will be used.

:::code-group
```ts [fixtures.test.ts]
import { test as base } from 'vitest'

const test = base.extend({
url: [
// default value if "url" is not defined in the config
'default',
// mark the fixure as "injected" to allow the override
{ injected: true },
],
})

test('works correctly', ({ url }) => {
// url is "/default" in "project-new"
// url is "/full" in "project-full"
// url is "/empty" in "project-empty"
})
```
```ts [vitest.workspace.ts]
import { defineWorkspace } from 'vitest/config'

export default defineWorkspace([
{
test: {
name: 'project-new',
},
},
{
test: {
name: 'project-full',
provide: {
url: '/full',
},
},
},
{
test: {
name: 'project-empty',
provide: {
url: '/empty',
},
},
},
])
```
:::

#### TypeScript

To provide fixture types for all your custom contexts, you can pass the fixtures type as a generic.
Expand All @@ -194,7 +246,7 @@ const myTest = test.extend<MyFixtures>({
archive: []
})

myTest('', (context) => {
myTest('types are defined correctly', (context) => {
expectTypeOf(context.todos).toEqualTypeOf<number[]>()
expectTypeOf(context.archive).toEqualTypeOf<number[]>()
})
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@vitest/monorepo",
"type": "module",
"version": "2.1.4",
"version": "2.2.0-beta.1",
"private": true,
"packageManager": "[email protected]",
"description": "Next generation testing framework powered by Vite",
Expand Down
28 changes: 7 additions & 21 deletions packages/browser/README.md
Original file line number Diff line number Diff line change
@@ -1,33 +1,19 @@
# @vitest/browser

Browser runner for Vitest.
[Browser runner](https://vitest.dev/guide/browser/) for Vitest.

> ⚠️ This package is **experimental**. While this package will be released along with other packages, it will not follow SemVer for breaking changes until we mark it as ready.
## Progress

Current Status: **Working in progress**

- [x] Init package and integration
- [x] Stub node packages for Vitest runtime
- [x] Works in development mode
- [x] Better log in terminal
- [x] Fulfill tests (using Browser only APIs, Vue and React components)
- [ ] Show progress and error on the browser page
- [x] Headless mode in CI
- [x] Docs

Related PRs

- [#1302](https://github.com/vitest-dev/vitest/pull/1302)

## Development Setup

At project root:

```bash
pnpm dev

cd test/browser
pnpm vitest --browser
# runs relevant tests for the browser mode
# useful to confirm everything works fine
pnpm test
# runs tests as the browser mode
# useful during development
pnpm test-fixtures
```
2 changes: 1 addition & 1 deletion packages/browser/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "@vitest/browser",
"type": "module",
"version": "2.1.4",
"version": "2.2.0-beta.1",
"description": "Browser running for Vitest",
"license": "MIT",
"funding": "https://opencollective.com/vitest",
Expand Down
Loading

0 comments on commit ed8a96e

Please sign in to comment.