diff --git a/docs/.vitepress/components/FeaturesList.vue b/docs/.vitepress/components/FeaturesList.vue
index c6d740800646..99bf99ac7701 100644
--- a/docs/.vitepress/components/FeaturesList.vue
+++ b/docs/.vitepress/components/FeaturesList.vue
@@ -23,6 +23,7 @@
happy-dom or jsdom for DOM mocking
Code coverage via c8 or istanbul
Rust-like in-source testing
+ Type Testing via expect-type
diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts
index 1193810fdf88..f93633767e36 100644
--- a/docs/.vitepress/config.ts
+++ b/docs/.vitepress/config.ts
@@ -115,6 +115,10 @@ export default defineConfig({
text: 'Features',
link: '/guide/features',
},
+ {
+ text: 'Testing Types',
+ link: '/guide/testing-types',
+ },
{
text: 'CLI',
link: '/guide/cli',
diff --git a/docs/api/index.md b/docs/api/index.md
index 97de0027eb95..d3547279cdb9 100644
--- a/docs/api/index.md
+++ b/docs/api/index.md
@@ -72,6 +72,10 @@ In Jest, `TestFunction` can also be of type `(done: DoneCallback) => void`. If t
})
```
+::: warning
+You cannot use this syntax, when using Vitest as [type checker](/guide/testing-types).
+:::
+
### test.runIf
- **Type:** `(condition: any) => Test`
@@ -89,6 +93,10 @@ In Jest, `TestFunction` can also be of type `(done: DoneCallback) => void`. If t
})
```
+::: warning
+You cannot use this syntax, when using Vitest as [type checker](/guide/testing-types).
+:::
+
### test.only
- **Type:** `(name: string, fn: TestFunction, timeout?: number) => void`
@@ -152,6 +160,10 @@ In Jest, `TestFunction` can also be of type `(done: DoneCallback) => void`. If t
})
```
+::: warning
+You cannot use this syntax, when using Vitest as [type checker](/guide/testing-types).
+:::
+
### test.todo
- **Type:** `(name: string) => void`
@@ -179,6 +191,10 @@ In Jest, `TestFunction` can also be of type `(done: DoneCallback) => void`. If t
})
```
+::: warning
+You cannot use this syntax, when using Vitest as [type checker](/guide/testing-types).
+:::
+
### test.each
- **Type:** `(cases: ReadonlyArray) => void`
- **Alias:** `it.each`
@@ -210,8 +226,29 @@ In Jest, `TestFunction` can also be of type `(done: DoneCallback) => void`. If t
// ✓ add(2, 1) -> 3
```
+ You can also access object properties with `$` prefix, if you are using objects as arguments:
+
+ ```ts
+ test.each([
+ { a: 1, b: 1, expected: 2 },
+ { a: 1, b: 2, expected: 3 },
+ { a: 2, b: 1, expected: 3 },
+ ])('add($a, $b) -> $expected', ({ a, b, expected }) => {
+ expect(a + b).toBe(expected)
+ })
+
+ // this will return
+ // ✓ add(1, 1) -> 2
+ // ✓ add(1, 2) -> 3
+ // ✓ add(2, 1) -> 3
+ ```
+
If you want to have access to `TestContext`, use `describe.each` with a single test.
+::: warning
+You cannot use this syntax, when using Vitest as [type checker](/guide/testing-types).
+:::
+
## bench
- **Type:** `(name: string, fn: BenchFunction, options?: BenchOptions) => void`
@@ -472,6 +509,10 @@ When you use `test` or `bench` in the top level of file, they are collected as p
describe.todo.concurrent(/* ... */) // or describe.concurrent.todo(/* ... */)
```
+::: warning
+You cannot use this syntax, when using Vitest as [type checker](/guide/testing-types).
+:::
+
### describe.shuffle
- **Type:** `(name: string, fn: TestFunction, options?: number | TestOptions) => void`
@@ -489,6 +530,10 @@ When you use `test` or `bench` in the top level of file, they are collected as p
`.skip`, `.only`, and `.todo` works with random suites.
+::: warning
+You cannot use this syntax, when using Vitest as [type checker](/guide/testing-types).
+:::
+
### describe.todo
- **Type:** `(name: string) => void`
@@ -526,6 +571,10 @@ When you use `test` or `bench` in the top level of file, they are collected as p
})
```
+::: warning
+You cannot use this syntax, when using Vitest as [type checker](/guide/testing-types).
+:::
+
## expect
- **Type:** `ExpectStatic & (actual: any) => Assertions`
@@ -547,6 +596,10 @@ When you use `test` or `bench` in the top level of file, they are collected as p
Also, `expect` can be used statically to access matchers functions, described later, and more.
+::: warning
+`expect` has no effect on testing types, if expression doesn't have a type error. If you want to use Vitest as [type checker](/guide/testing-types), use [`expectTypeOf`](#expecttypeof) or [`assertType`](#asserttype).
+:::
+
### not
Using `not` will negate the assertion. For example, this code asserts that an `input` value is not equal to `2`. If it's equal, assertion will throw an error, and the test will fail.
@@ -1776,9 +1829,521 @@ When you use `test` or `bench` in the top level of file, they are collected as p
If you want to know more, checkout [guide on extending matchers](/guide/extending-matchers).
:::
+## expectTypeOf
+
+- **Type:** `(a: unknown) => ExpectTypeOf`
+
+### not
+
+ - **Type:** `ExpectTypeOf`
+
+ You can negate all assertions, using `.not` property.
+
+### toEqualTypeOf
+
+ - **Type:** `(expected: T) => void`
+
+ This matcher will check, if types are fully equal to each other. This matcher will not fail, if two objects have different values, but the same type, but will fail, if object is missing a property.
+
+ ```ts
+ import { expectTypeOf } from 'vitest'
+
+ expectTypeOf({ a: 1 }).toEqualTypeOf<{ a: number }>()
+ expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 1 })
+ expectTypeOf({ a: 1 }).toEqualTypeOf({ a: 2 })
+ expectTypeOf({ a: 1, b: 1 }).not.toEqualTypeOf<{ a: number }>()
+ ```
+
+### toMatchTypeOf
+
+ - **Type:** `(expected: T) => void`
+
+ This matcher checks if expect type extends provided type. It is different from `toEqual` and is more similar to expect's `toMatch`. With this matcher you can check, if an object "matches" a type.
+
+ ```ts
+ import { expectTypeOf } from 'vitest'
+
+ expectTypeOf({ a: 1, b: 1 }).toMatchTypeOf({ a: 1 })
+ expectTypeOf().toMatchTypeOf()
+ expectTypeOf().not.toMatchTypeOf()
+ ```
+
+### extract
+
+ - **Type:** `ExpectTypeOf`
+
+ You can use `.extract` to narrow down types for further testing.
+
+ ```ts
+ import { expectTypeOf } from 'vitest'
+
+ type ResponsiveProp = T | T[] | { xs?: T; sm?: T; md?: T }
+ const getResponsiveProp = (_props: T): ResponsiveProp => ({})
+ interface CSSProperties { margin?: string; padding?: string }
+
+ const cssProperties: CSSProperties = { margin: '1px', padding: '2px' }
+
+ expectTypeOf(getResponsiveProp(cssProperties))
+ .extract<{ xs?: any }>() // extracts the last type from a union
+ .toEqualTypeOf<{ xs?: CSSProperties; sm?: CSSProperties; md?: CSSProperties }>()
+
+ expectTypeOf(getResponsiveProp(cssProperties))
+ .extract() // extracts an array from a union
+ .toEqualTypeOf()
+ ```
+
+ ::: warning
+ If no type is found in the union, `.extract` will return `never`.
+ :::
+
+### exclude
+
+ - **Type:** `ExpectTypeOf`
+
+ You can use `.exclude` to remove types from a union for further testing.
+
+ ```ts
+ import { expectTypeOf } from 'vitest'
+
+ type ResponsiveProp = T | T[] | { xs?: T; sm?: T; md?: T }
+ const getResponsiveProp = (_props: T): ResponsiveProp => ({})
+ interface CSSProperties { margin?: string; padding?: string }
+
+ const cssProperties: CSSProperties = { margin: '1px', padding: '2px' }
+
+ expectTypeOf(getResponsiveProp(cssProperties))
+ .exclude()
+ .exclude<{ xs?: unknown }>() // or just .exclude()
+ .toEqualTypeOf()
+ ```
+
+ ::: warning
+ If no type is found in the union, `.exclude` will return `never`.
+ :::
+
+### returns
+
+ - **Type:** `ExpectTypeOf`
+
+ You can use `.returns` to extract return value of a function type.
+
+ ```ts
+ import { expectTypeOf } from 'vitest'
+
+ expectTypeOf(() => {}).returns.toBeVoid()
+ expectTypeOf((a: number) => [a, a]).returns.toEqualTypeOf([1, 2])
+ ```
+
+ ::: warning
+ If used on a non-function type, it will return `never`, so you won't be able to chain it with other matchers.
+ :::
+
+### parameters
+
+ - **Type:** `ExpectTypeOf`
+
+ You can extract function arguments with `.parameters` to perform assertions on its value. Parameters are returned as an array.
+
+ ```ts
+ import { expectTypeOf } from 'vitest'
+
+ type NoParam = () => void
+ type HasParam = (s: string) => void
+
+ expectTypeOf().parameters.toEqualTypeOf<[]>()
+ expectTypeOf().parameters.toEqualTypeOf<[string]>()
+ ```
+
+ ::: warning
+ If used on a non-function type, it will return `never`, so you won't be able to chain it with other matchers.
+ :::
+
+ ::: tip
+ You can also use [`.toBeCallableWith`](#tobecallablewith) matcher as a more expressive assertion.
+ :::
+
+### parameter
+
+ - **Type:** `(nth: number) => ExpectTypeOf`
+
+ You can extract a certain function argument with `.parameter(number)` call to perform other assertions on it.
+
+ ```ts
+ import { expectTypeOf } from 'vitest'
+
+ const foo = (a: number, b: string) => [a, b]
+
+ expectTypeOf(foo).parameter(0).toBeNumber()
+ expectTypeOf(foo).parameter(1).toBeString()
+ ```
+
+ ::: warning
+ If used on a non-function type, it will return `never`, so you won't be able to chain it with other matchers.
+ :::
+
+### constructorParameters
+
+ - **Type:** `ExpectTypeOf`
+
+ You can extract constructor parameters as an array of values and perform assertions on them with this method.
+
+ ```ts
+ import { expectTypeOf } from 'vitest'
+
+ expectTypeOf(Date).constructorParameters.toEqualTypeOf<[] | [string | number | Date]>()
+ ```
+
+ ::: warning
+ If used on a non-function type, it will return `never`, so you won't be able to chain it with other matchers.
+ :::
+
+ ::: tip
+ You can also use [`.toBeConstructibleWith`](#tobeconstructiblewith) matcher as a more expressive assertion.
+ :::
+
+### instance
+
+ - **Type:** `ExpectTypeOf`
+
+ This property gives access to matchers that can be performed on an instance of the provided class.
+
+ ```ts
+ import { expectTypeOf } from 'vitest'
+
+ expectTypeOf(Date).instance.toHaveProperty('toISOString')
+ ```
+
+ ::: warning
+ If used on a non-function type, it will return `never`, so you won't be able to chain it with other matchers.
+ :::
+
+### items
+
+ - **Type:** `ExpectTypeOf`
+
+ You can get array item type with `.items` to perform further assertions.
+
+ ```ts
+ import { expectTypeOf } from 'vitest'
+
+ expectTypeOf([1, 2, 3]).items.toEqualTypeOf()
+ expectTypeOf([1, 2, 3]).items.not.toEqualTypeOf()
+ ```
+
+### resolves
+
+ - **Type:** `ExpectTypeOf`
+
+ This matcher extracts resolved value of a `Promise`, so you can perform other assertions on it.
+
+ ```ts
+ import { expectTypeOf } from 'vitest'
+
+ const asyncFunc = async () => 123
+
+ expectTypeOf(asyncFunc).returns.resolves.toBeNumber()
+ expectTypeOf(Promise.resolve('string')).resolves.toBeString()
+ ```
+
+ ::: warning
+ If used on a non-promise type, it will return `never`, so you won't be able to chain it with other matchers.
+ :::
+
+### guards
+
+ - **Type:** `ExpectTypeOf`
+
+ This matcher extracts guard value (e.g., `v is number`), so you can perform assertions on it.
+
+ ```ts
+ import { expectTypeOf } from 'vitest'
+
+ const isString = (v: any): v is string => typeof v === 'string'
+ expectTypeOf(isString).guards.toBeString()
+ ```
+
+ ::: warning
+ Returns `never`, if the value is not a guard function, so you won't be able to chain it with other matchers.
+ :::
+
+### asserts
+
+ - **Type:** `ExpectTypeOf`
+
+ This matcher extracts assert value (e.g., `assert v is number`), so you can perform assertions on it.
+
+ ```ts
+ import { expectTypeOf } from 'vitest'
+
+ const assertNumber = (v: any): asserts v is number => {
+ if (typeof v !== 'number')
+ throw new TypeError('Nope !')
+ }
+
+ expectTypeOf(assertNumber).asserts.toBeNumber()
+ ```
+
+ ::: warning
+ Returns `never`, if the value is not an assert function, so you won't be able to chain it with other matchers.
+ :::
+
+### toBeAny
+
+ - **Type:** `() => void`
+
+ With this matcher you can check, if provided type is `any` type. If the type is too specific, the test will fail.
+
+ ```ts
+ import { expectTypeOf } from 'vitest'
+
+ expectTypeOf().toBeAny()
+ expectTypeOf({} as any).toBeAny()
+ expectTypeOf('string').not.toBeAny()
+ ```
+
+### toBeUnknown
+
+ - **Type:** `() => void`
+
+ This matcher checks, if provided type is `unknown` type.
+
+ ```ts
+ import { expectTypeOf } from 'vitest'
+
+ expectTypeOf().toBeUnknown()
+ expectTypeOf({} as unknown).toBeUnknown()
+ expectTypeOf('string').not.toBeUnknown()
+ ```
+
+### toBeNever
+
+ - **Type:** `() => void`
+
+ This matcher checks, if provided type is a `never` type.
+
+ ```ts
+ import { expectTypeOf } from 'vitest'
+
+ expectTypeOf().toBeNever()
+ expectTypeOf((): never => {}).returns.toBeNever()
+ ```
+
+### toBeFunction
+
+ - **Type:** `() => void`
+
+ This matcher checks, if provided type is a `functon`.
+
+ ```ts
+ import { expectTypeOf } from 'vitest'
+
+ expectTypeOf(42).not.toBeFunction()
+ expectTypeOf((): never => {}).toBeFunction()
+ ```
+
+### toBeObject
+
+ - **Type:** `() => void`
+
+ This matcher checks, if provided type is an `object`.
+
+ ```ts
+ import { expectTypeOf } from 'vitest'
+
+ expectTypeOf(42).not.toBeObject()
+ expectTypeOf({}).toBeObject()
+ ```
+
+### toBeArray
+
+ - **Type:** `() => void`
+
+ This matcher checks, if provided type is `Array`.
+
+ ```ts
+ import { expectTypeOf } from 'vitest'
+
+ expectTypeOf(42).not.toBeArray()
+ expectTypeOf([]).toBeArray()
+ expectTypeOf([1, 2]).toBeArray()
+ expectTypeOf([{}, 42]).toBeArray()
+ ```
+
+### toBeString
+
+ - **Type:** `() => void`
+
+ This matcher checks, if provided type is a `string`.
+
+ ```ts
+ import { expectTypeOf } from 'vitest'
+
+ expectTypeOf(42).not.toBeArray()
+ expectTypeOf([]).toBeArray()
+ expectTypeOf([1, 2]).toBeArray()
+ expectTypeOf().toBeArray()
+ ```
+
+### toBeBoolean
+
+ - **Type:** `() => void`
+
+ This matcher checks, if provided type is `boolean`.
+
+ ```ts
+ import { expectTypeOf } from 'vitest'
+
+ expectTypeOf(42).not.toBeBoolean()
+ expectTypeOf(true).toBeBoolean()
+ expectTypeOf().toBeBoolean()
+ ```
+
+### toBeVoid
+
+ - **Type:** `() => void`
+
+ This matcher checks, if provided type is `void`.
+
+ ```ts
+ import { expectTypeOf } from 'vitest'
+
+ expectTypeOf(() => {}).returns.toBeVoid()
+ expectTypeOf().toBeVoid()
+ ```
+
+### toBeSymbol
+
+ - **Type:** `() => void`
+
+ This matcher checks, if provided type is a `symbol`.
+
+ ```ts
+ import { expectTypeOf } from 'vitest'
+
+ expectTypeOf(Symbol(1)).toBeSymbol()
+ expectTypeOf().toBeSymbol()
+ ```
+
+### toBeNull
+
+ - **Type:** `() => void`
+
+ This matcher checks, if provided type is `null`.
+
+ ```ts
+ import { expectTypeOf } from 'vitest'
+
+ expectTypeOf(null).toBeNull()
+ expectTypeOf().toBeNull()
+ expectTypeOf(undefined).not.toBeNull()
+ ```
+
+### toBeUndefined
+
+ - **Type:** `() => void`
+
+ This matcher checks, if provided type is `undefined`.
+
+ ```ts
+ import { expectTypeOf } from 'vitest'
+
+ expectTypeOf(undefined).toBeUndefined()
+ expectTypeOf().toBeUndefined()
+ expectTypeOf(null).not.toBeUndefined()
+ ```
+
+### toBeNullable
+
+ - **Type:** `() => void`
+
+ This matcher checks, if you can use `null` or `undefined` with provided type.
+
+ ```ts
+ import { expectTypeOf } from 'vitest'
+
+ expectTypeOf<1 | undefined>().toBeNullable()
+ expectTypeOf<1 | null>().toBeNullable()
+ expectTypeOf<1 | undefined | null>().toBeNullable()
+ ```
+
+### toBeCallableWith
+
+ - **Type:** `() => void`
+
+ This matcher ensures you can call provided function with a set of parameters.
+
+ ```ts
+ import { expectTypeOf } from 'vitest'
+
+ type NoParam = () => void
+ type HasParam = (s: string) => void
+
+ expectTypeOf().toBeCallableWith()
+ expectTypeOf().toBeCallableWith('some string')
+ ```
+
+ ::: warning
+ If used on a non-function type, it will return `never`, so you won't be able to chain it with other matchers.
+ :::
+
+### toBeConstructibleWith
+
+ - **Type:** `() => void`
+
+ This matcher ensures you can create a new instance with a set of constructor parameters.
+
+ ```ts
+ import { expectTypeOf } from 'vitest'
+
+ expectTypeOf(Date).toBeConstructibleWith(new Date())
+ expectTypeOf(Date).toBeConstructibleWith('01-01-2000')
+ ```
+
+ ::: warning
+ If used on a non-function type, it will return `never`, so you won't be able to chain it with other matchers.
+ :::
+
+### toHaveProperty
+
+ - **Type:** `(property: K) => ExpectTypeOf`
+
+ This matcher checks if a property exists on provided object. If it exists, it also returns the same set of matchers for the type of this property, so you can chain assertions one after another.
+
+ ```ts
+ import { expectTypeOf } from 'vitest'
+
+ const obj = { a: 1, b: '' }
+
+ expectTypeOf(obj).toHaveProperty('a')
+ expectTypeOf(obj).not.toHaveProperty('c')
+
+ expectTypeOf(obj).toHaveProperty('a').toBeNumber()
+ expectTypeOf(obj).toHaveProperty('b').toBeString()
+ expectTypeOf(obj).toHaveProperty('a').not.toBeString()
+ ```
+
+## assertType
+
+ - **Type:** `(value: T): void`
+
+ You can use this function as an alternative for `expectTypeOf` to easily assert that argument type is equal to provided generic.
+
+ ```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))
+ ```
+
## Setup and Teardown
-These functions allow you to hook into the life cycle of tests to avoid repeating setup and teardown code. They apply to the current context: the file if they are used at the top-level or the current suite if they are inside a `describe` block.
+These functions allow you to hook into the life cycle of tests to avoid repeating setup and teardown code. They apply to the current context: the file if they are used at the top-level or the current suite if they are inside a `describe` block. These hooks are not called, when you are running Vitest as a type checker.
### beforeEach
@@ -1970,9 +2535,9 @@ Vitest provides utility functions to help you out through it's **vi** helper. Yo
- **Type**: `(path: string, factory?: () => unknown) => void`
- Makes all `imports` to passed module to be mocked. Inside a path you _can_ use configured Vite aliases.
+ Makes all `imports` to passed module to be mocked. Inside a path you _can_ use configured Vite aliases. The call to `vi.mock` is hoisted, so it doesn't matter where you call it. It will always be executed before all imports.
- - If `factory` is defined, will return its result. Factory function can be asynchronous. You may call [`vi.importActual`](#vi-importactual) inside to get the original module. The call to `vi.mock` is hoisted to the top of the file, so you don't have access to variables declared in the global file scope!
+ - If `factory` is defined, will return its result. Factory function can be asynchronous. You may call [`vi.importActual`](#vi-importactual) inside to get the original module. Since the call to `vi.mock` is hoisted, you don't have access to variables declared in the global file scope!
- If mocking a module with a default export, you'll need to provide a `default` key within the returned factory function object. This is an ES modules specific caveat, therefore `jest` documentation may differ as `jest` uses commonJS modules. *Example:*
```ts
diff --git a/docs/config/index.md b/docs/config/index.md
index c28425929c18..473ac1d51af7 100644
--- a/docs/config/index.md
+++ b/docs/config/index.md
@@ -849,3 +849,58 @@ Vitest usually uses cache to sort tests, so long running tests start earlier - t
- **Default**: `Date.now()`
Sets the randomization seed, if tests are running in random order.
+
+### typecheck
+
+Options for configuring [typechecking](/guide/testing-types) test environment.
+
+#### typecheck.checker
+
+- **Type**: `'tsc' | 'vue-tsc' | string`
+- **Default**: `tsc`
+
+What tools to use for type checking. Vitest will spawn a process with certain parameters for easier parsing, depending on the type. Checker should implement the same output format as `tsc`.
+
+You need to have a package installed to use typecheker:
+
+- `tsc` requires `typescript` package
+- `vue-tsc` requires `vue-tsc` package
+
+You can also pass down a path to custom binary or command name that produces the same output as `tsc --noEmit --pretty false`.
+
+#### typecheck.include
+
+- **Type**: `string[]`
+- **Default**: `['**/*.{test,spec}-d.{ts,js}']`
+
+Glob pattern for files that should be treated as test files
+
+#### typecheck.exclude
+
+- **Type**: `string[]`
+- **Default**: `['**/node_modules/**', '**/dist/**', '**/cypress/**', '**/.{idea,git,cache,output,temp}/**']`
+
+Glob pattern for files that should not be treated as test files
+
+#### typecheck.allowJs
+
+- **Type**: `boolean`
+- **Default**: `false`
+
+Check JS files that have `@ts-check` comment. If you have it enabled in tsconfig, this will not overwrite it.
+
+#### typecheck.ignoreSourceErrors
+
+- **Type**: `boolean`
+- **Default**: `false`
+
+Do not fail, if Vitest found errors outside the test files. This will not show you non-test errors at all.
+
+By default, if Vitest finds source error, it will fail test suite.
+
+#### typecheck.tsconfig
+
+- **Type**: `string`
+- **Default**: _tries to find closest tsconfig.json_
+
+Path to custom tsconfig, relative to the project root.
diff --git a/docs/guide/features.md b/docs/guide/features.md
index 5bebfafce743..6aed1de35eb6 100644
--- a/docs/guide/features.md
+++ b/docs/guide/features.md
@@ -200,3 +200,20 @@ describe('sort', () => {
})
})
```
+
+## Type Testing experimental
+
+Since Vitest 0.25.0 you can [write tests](/guide/testing-types) to catch type regressions. Vitest comes with [`expect-type`](https://github.com/mmkal/expect-type) package to provide you with a similar and easy to understand API.
+
+```ts
+import { assertType, expectTypeOf } from 'vitest'
+import { mount } from './mount.js'
+
+test('my types work properly', () => {
+ expectTypeOf(mount).toBeFunction()
+ expectTypeOf(mount).parameter(0).toMatchTypeOf<{ name: string }>()
+
+ // @ts-expect-error name is a string
+ assertType(mount({ name: 42 }))
+})
+```
diff --git a/docs/guide/testing-types.md b/docs/guide/testing-types.md
new file mode 100644
index 000000000000..35340ea892d5
--- /dev/null
+++ b/docs/guide/testing-types.md
@@ -0,0 +1,92 @@
+---
+title: Testing Types | Guide
+---
+
+# Testing Types
+
+Vitest allows you to write tests for your types, using `expectTypeOf` or `assertType` syntaxes. By default all tests inside `*.test-d.ts` files are considered type tests, but you can change it with [`typecheck.include`](/config/#typecheck-include) config option.
+
+Under the hood Vitest calls `tsc` or `vue-tsc`, depending on your config, and parses results. Vitest will also print out type errors in your source code, if it finds any. You can disable it with [`typecheck.ignoreSourceErrors`](/config/#typecheck-ignoresourceerrors) config option.
+
+Keep in mind that Vitest doesn't run or compile these files, they are only statically analyzed by the compiler, and because of that you cannot use any dynamic statements. Meaning, you cannot use dynamic test names, and `test.each`, `test.runIf`, `test.skipIf`, `test.each`, `test.concurrent` APIs. But you can use other APIs, like `test`, `describe`, `.only`, `.skip` and `.todo`.
+
+Using CLI flags, like `--allowOnly` and `-t` are also supported for type checking.
+
+```ts
+import { assertType, expectTypeOf } from 'vitest'
+import { mount } from './mount.js'
+
+test('my types work properly', () => {
+ expectTypeOf(mount).toBeFunction()
+ expectTypeOf(mount).parameter(0).toMatchTypeOf<{ name: string }>()
+
+ // @ts-expect-error name is a string
+ assertType(mount({ name: 42 }))
+})
+```
+
+Any type error triggered inside a test file will be treated as a test error, so you can use any type trick you want to test types of your project.
+
+You can see a list of possible matchers in [API section](/api/#expecttypeof).
+
+## Reading Errors
+
+If you are using `expectTypeOf` API, you might notice hard to read errors or unexpected:
+
+```ts
+expectTypeOf(1).toEqualTypeOf()
+// ^^^^^^^^^^^^^^^^^^^^^^
+// index-c3943160.d.ts(90, 20): Arguments for the rest parameter 'MISMATCH' were not provided.
+```
+
+This is due to how [`expect-type`](https://github.com/mmkal/expect-type) handles type errors.
+
+Unfortunately, TypeScript doesn't provide type metadata without patching, so we cannot provide useful error messages at this point, but there are works in TypeScript project to fix this. If you want better messages, please, ask TypeScript team to have a look at mentioned PR.
+
+If you find it hard working with `expectTypeOf` API and figuring out errors, you can always use more simple `assertType` API:
+
+```ts
+const answer = 42
+
+assertType(answer)
+// @ts-expect-error answer is not a string
+assertType(answer)
+```
+
+::: tip
+When using `@ts-expect-error` syntax, you might want to make sure that you didn't make a typo. You can do that by including your type files in [`test.include`](/config/#include) config option, so Vitest will also actually *run* these tests and fail with `ReferenceError`.
+
+This will pass, because it expects an error, but the word “answer” has a typo, so it's a false positive error:
+
+```ts
+// @ts-expect-error answer is not a string
+assertType(answr) //
+```
+:::
+
+## Run typechecking
+
+Add this command to your `scripts` section in `package.json`:
+
+```json
+{
+ "scripts": {
+ "typecheck": "vitest typecheck"
+ }
+}
+```
+
+Now you can run typecheck:
+
+```sh
+# npm
+npm run typecheck
+
+# yarn
+yarn typecheck
+
+# pnpm
+pnpm run typecheck
+```
+
+Vitest uses `tsc --noEmit` or `vue-tsc --noEmit`, depending on your configuration, so you can remove these scripts from your pipeline.
diff --git a/packages/ui/client/composables/summary.ts b/packages/ui/client/composables/summary.ts
index aa8eab5e86ad..198f4bfc2ea2 100644
--- a/packages/ui/client/composables/summary.ts
+++ b/packages/ui/client/composables/summary.ts
@@ -1,5 +1,5 @@
import { hasFailedSnapshot } from '@vitest/ws-client'
-import type { Benchmark, Task, Test } from 'vitest/src'
+import type { Benchmark, Task, Test, TypeCheck } from 'vitest/src'
import { files, testRunState } from '~/composables/client'
type Nullable = T | null | undefined
@@ -52,9 +52,9 @@ function toArray(array?: Nullable>): Array {
return array
return [array]
}
-function isAtomTest(s: Task): s is Test | Benchmark {
- return (s.type === 'test' || s.type === 'benchmark')
+function isAtomTest(s: Task): s is Test | Benchmark | TypeCheck {
+ return (s.type === 'test' || s.type === 'benchmark' || s.type === 'typecheck')
}
-function getTests(suite: Arrayable): (Test | Benchmark)[] {
+function getTests(suite: Arrayable): (Test | Benchmark | TypeCheck)[] {
return toArray(suite).flatMap(s => isAtomTest(s) ? [s] : s.tasks.flatMap(c => isAtomTest(c) ? [c] : getTests(c)))
}
diff --git a/packages/vite-node/package.json b/packages/vite-node/package.json
index 96ce0e85ba50..ac8a7c1b8ac1 100644
--- a/packages/vite-node/package.json
+++ b/packages/vite-node/package.json
@@ -78,11 +78,13 @@
"debug": "^4.3.4",
"mlly": "^0.5.16",
"pathe": "^0.2.0",
+ "source-map": "^0.6.1",
"source-map-support": "^0.5.21",
"vite": "^3.0.0"
},
"devDependencies": {
"@types/debug": "^4.1.7",
+ "@types/source-map": "^0.5.7",
"@types/source-map-support": "^0.5.6",
"cac": "^6.7.14",
"picocolors": "^1.0.0",
diff --git a/packages/vitest/LICENSE.md b/packages/vitest/LICENSE.md
index e3fc4e6dab15..06de2f4cb5c4 100644
--- a/packages/vitest/LICENSE.md
+++ b/packages/vitest/LICENSE.md
@@ -197,35 +197,6 @@ Repository: https://github.com/sinonjs/fake-timers.git
---------------------------------------
-## acorn
-License: MIT
-By: Marijn Haverbeke, Ingvar Stepanyan, Adrian Heine
-Repository: https://github.com/acornjs/acorn.git
-
-> MIT License
->
-> Copyright (C) 2012-2022 by various contributors (see AUTHORS)
->
-> Permission is hereby granted, free of charge, to any person obtaining a copy
-> of this software and associated documentation files (the "Software"), to deal
-> in the Software without restriction, including without limitation the rights
-> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-> copies of the Software, and to permit persons to whom the Software is
-> furnished to do so, subject to the following conditions:
->
-> The above copyright notice and this permission notice shall be included in
-> all copies or substantial portions of the Software.
->
-> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-> THE SOFTWARE.
-
----------------------------------------
-
## ansi-escapes
License: MIT
By: Sindre Sorhus
@@ -603,6 +574,214 @@ Repository: sindresorhus/execa
---------------------------------------
+## expect-type
+License: Apache-2.0
+Repository: https://github.com/mmkal/expect-type.git
+
+> Apache License
+> Version 2.0, January 2004
+> http://www.apache.org/licenses/
+>
+> TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+>
+> 1. Definitions.
+>
+> "License" shall mean the terms and conditions for use, reproduction,
+> and distribution as defined by Sections 1 through 9 of this document.
+>
+> "Licensor" shall mean the copyright owner or entity authorized by
+> the copyright owner that is granting the License.
+>
+> "Legal Entity" shall mean the union of the acting entity and all
+> other entities that control, are controlled by, or are under common
+> control with that entity. For the purposes of this definition,
+> "control" means (i) the power, direct or indirect, to cause the
+> direction or management of such entity, whether by contract or
+> otherwise, or (ii) ownership of fifty percent (50%) or more of the
+> outstanding shares, or (iii) beneficial ownership of such entity.
+>
+> "You" (or "Your") shall mean an individual or Legal Entity
+> exercising permissions granted by this License.
+>
+> "Source" form shall mean the preferred form for making modifications,
+> including but not limited to software source code, documentation
+> source, and configuration files.
+>
+> "Object" form shall mean any form resulting from mechanical
+> transformation or translation of a Source form, including but
+> not limited to compiled object code, generated documentation,
+> and conversions to other media types.
+>
+> "Work" shall mean the work of authorship, whether in Source or
+> Object form, made available under the License, as indicated by a
+> copyright notice that is included in or attached to the work
+> (an example is provided in the Appendix below).
+>
+> "Derivative Works" shall mean any work, whether in Source or Object
+> form, that is based on (or derived from) the Work and for which the
+> editorial revisions, annotations, elaborations, or other modifications
+> represent, as a whole, an original work of authorship. For the purposes
+> of this License, Derivative Works shall not include works that remain
+> separable from, or merely link (or bind by name) to the interfaces of,
+> the Work and Derivative Works thereof.
+>
+> "Contribution" shall mean any work of authorship, including
+> the original version of the Work and any modifications or additions
+> to that Work or Derivative Works thereof, that is intentionally
+> submitted to Licensor for inclusion in the Work by the copyright owner
+> or by an individual or Legal Entity authorized to submit on behalf of
+> the copyright owner. For the purposes of this definition, "submitted"
+> means any form of electronic, verbal, or written communication sent
+> to the Licensor or its representatives, including but not limited to
+> communication on electronic mailing lists, source code control systems,
+> and issue tracking systems that are managed by, or on behalf of, the
+> Licensor for the purpose of discussing and improving the Work, but
+> excluding communication that is conspicuously marked or otherwise
+> designated in writing by the copyright owner as "Not a Contribution."
+>
+> "Contributor" shall mean Licensor and any individual or Legal Entity
+> on behalf of whom a Contribution has been received by Licensor and
+> subsequently incorporated within the Work.
+>
+> 2. Grant of Copyright License. Subject to the terms and conditions of
+> this License, each Contributor hereby grants to You a perpetual,
+> worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+> copyright license to reproduce, prepare Derivative Works of,
+> publicly display, publicly perform, sublicense, and distribute the
+> Work and such Derivative Works in Source or Object form.
+>
+> 3. Grant of Patent License. Subject to the terms and conditions of
+> this License, each Contributor hereby grants to You a perpetual,
+> worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+> (except as stated in this section) patent license to make, have made,
+> use, offer to sell, sell, import, and otherwise transfer the Work,
+> where such license applies only to those patent claims licensable
+> by such Contributor that are necessarily infringed by their
+> Contribution(s) alone or by combination of their Contribution(s)
+> with the Work to which such Contribution(s) was submitted. If You
+> institute patent litigation against any entity (including a
+> cross-claim or counterclaim in a lawsuit) alleging that the Work
+> or a Contribution incorporated within the Work constitutes direct
+> or contributory patent infringement, then any patent licenses
+> granted to You under this License for that Work shall terminate
+> as of the date such litigation is filed.
+>
+> 4. Redistribution. You may reproduce and distribute copies of the
+> Work or Derivative Works thereof in any medium, with or without
+> modifications, and in Source or Object form, provided that You
+> meet the following conditions:
+>
+> (a) You must give any other recipients of the Work or
+> Derivative Works a copy of this License; and
+>
+> (b) You must cause any modified files to carry prominent notices
+> stating that You changed the files; and
+>
+> (c) You must retain, in the Source form of any Derivative Works
+> that You distribute, all copyright, patent, trademark, and
+> attribution notices from the Source form of the Work,
+> excluding those notices that do not pertain to any part of
+> the Derivative Works; and
+>
+> (d) If the Work includes a "NOTICE" text file as part of its
+> distribution, then any Derivative Works that You distribute must
+> include a readable copy of the attribution notices contained
+> within such NOTICE file, excluding those notices that do not
+> pertain to any part of the Derivative Works, in at least one
+> of the following places: within a NOTICE text file distributed
+> as part of the Derivative Works; within the Source form or
+> documentation, if provided along with the Derivative Works; or,
+> within a display generated by the Derivative Works, if and
+> wherever such third-party notices normally appear. The contents
+> of the NOTICE file are for informational purposes only and
+> do not modify the License. You may add Your own attribution
+> notices within Derivative Works that You distribute, alongside
+> or as an addendum to the NOTICE text from the Work, provided
+> that such additional attribution notices cannot be construed
+> as modifying the License.
+>
+> You may add Your own copyright statement to Your modifications and
+> may provide additional or different license terms and conditions
+> for use, reproduction, or distribution of Your modifications, or
+> for any such Derivative Works as a whole, provided Your use,
+> reproduction, and distribution of the Work otherwise complies with
+> the conditions stated in this License.
+>
+> 5. Submission of Contributions. Unless You explicitly state otherwise,
+> any Contribution intentionally submitted for inclusion in the Work
+> by You to the Licensor shall be under the terms and conditions of
+> this License, without any additional terms or conditions.
+> Notwithstanding the above, nothing herein shall supersede or modify
+> the terms of any separate license agreement you may have executed
+> with Licensor regarding such Contributions.
+>
+> 6. Trademarks. This License does not grant permission to use the trade
+> names, trademarks, service marks, or product names of the Licensor,
+> except as required for reasonable and customary use in describing the
+> origin of the Work and reproducing the content of the NOTICE file.
+>
+> 7. Disclaimer of Warranty. Unless required by applicable law or
+> agreed to in writing, Licensor provides the Work (and each
+> Contributor provides its Contributions) on an "AS IS" BASIS,
+> WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+> implied, including, without limitation, any warranties or conditions
+> of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+> PARTICULAR PURPOSE. You are solely responsible for determining the
+> appropriateness of using or redistributing the Work and assume any
+> risks associated with Your exercise of permissions under this License.
+>
+> 8. Limitation of Liability. In no event and under no legal theory,
+> whether in tort (including negligence), contract, or otherwise,
+> unless required by applicable law (such as deliberate and grossly
+> negligent acts) or agreed to in writing, shall any Contributor be
+> liable to You for damages, including any direct, indirect, special,
+> incidental, or consequential damages of any character arising as a
+> result of this License or out of the use or inability to use the
+> Work (including but not limited to damages for loss of goodwill,
+> work stoppage, computer failure or malfunction, or any and all
+> other commercial damages or losses), even if such Contributor
+> has been advised of the possibility of such damages.
+>
+> 9. Accepting Warranty or Additional Liability. While redistributing
+> the Work or Derivative Works thereof, You may choose to offer,
+> and charge a fee for, acceptance of support, warranty, indemnity,
+> or other liability obligations and/or rights consistent with this
+> License. However, in accepting such obligations, You may act only
+> on Your own behalf and on Your sole responsibility, not on behalf
+> of any other Contributor, and only if You agree to indemnify,
+> defend, and hold each Contributor harmless for any liability
+> incurred by, or claims asserted against, such Contributor by reason
+> of your accepting any such warranty or additional liability.
+>
+> END OF TERMS AND CONDITIONS
+>
+> APPENDIX: How to apply the Apache License to your work.
+>
+> To apply the Apache License to your work, attach the following
+> boilerplate notice, with the fields enclosed by brackets "[]"
+> replaced with your own identifying information. (Don't include
+> the brackets!) The text should be enclosed in the appropriate
+> comment syntax for the file format. We also recommend that a
+> file or class name and description of purpose be included on the
+> same "printed page" as the copyright notice for easier
+> identification within third-party archives.
+>
+> Copyright [yyyy] [name of copyright owner]
+>
+> Licensed under the Apache License, Version 2.0 (the "License");
+> you may not use this file except in compliance with the License.
+> You may obtain a copy of the License at
+>
+> http://www.apache.org/licenses/LICENSE-2.0
+>
+> Unless required by applicable law or agreed to in writing, software
+> distributed under the License is distributed on an "AS IS" BASIS,
+> WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+> See the License for the specific language governing permissions and
+> limitations under the License.
+
+---------------------------------------
+
## fast-glob
License: MIT
By: Denis Malinochkin
@@ -739,6 +918,35 @@ Repository: sindresorhus/get-stream
---------------------------------------
+## get-tsconfig
+License: MIT
+By: Hiroki Osame
+Repository: privatenumber/get-tsconfig
+
+> MIT License
+>
+> Copyright (c) Hiroki Osame
+>
+> Permission is hereby granted, free of charge, to any person obtaining a copy
+> of this software and associated documentation files (the "Software"), to deal
+> in the Software without restriction, including without limitation the rights
+> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+> copies of the Software, and to permit persons to whom the Software is
+> furnished to do so, subject to the following conditions:
+>
+> The above copyright notice and this permission notice shall be included in all
+> copies or substantial portions of the Software.
+>
+> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+> SOFTWARE.
+
+---------------------------------------
+
## glob-parent
License: ISC
By: Gulp Team, Elan Shanker, Blaine Bublitz
@@ -1286,7 +1494,7 @@ Repository: sindresorhus/mimic-fn
> MIT License
>
-> Copyright (c) Sindre Sorhus (sindresorhus.com)
+> Copyright (c) Sindre Sorhus (https://sindresorhus.com)
>
> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
>
diff --git a/packages/vitest/globals.d.ts b/packages/vitest/globals.d.ts
index dbeb9fca262b..c1096c5501ec 100644
--- a/packages/vitest/globals.d.ts
+++ b/packages/vitest/globals.d.ts
@@ -3,6 +3,8 @@ declare global {
const test: typeof import('vitest')['test']
const describe: typeof import('vitest')['describe']
const it: typeof import('vitest')['it']
+ const expectTypeOf: typeof import('vitest')['expectTypeOf']
+ const assertType: typeof import('vitest')['assertType']
const expect: typeof import('vitest')['expect']
const assert: typeof import('vitest')['assert']
const vitest: typeof import('vitest')['vitest']
diff --git a/packages/vitest/package.json b/packages/vitest/package.json
index 7ed1b0719985..ace20ccff008 100644
--- a/packages/vitest/package.json
+++ b/packages/vitest/package.json
@@ -108,9 +108,12 @@
"@types/chai": "^4.3.3",
"@types/chai-subset": "^1.3.3",
"@types/node": "*",
+ "acorn": "^8.8.0",
+ "acorn-walk": "^8.2.0",
"chai": "^4.3.6",
"debug": "^4.3.4",
"local-pkg": "^0.4.2",
+ "source-map": "^0.6.1",
"strip-literal": "^0.4.2",
"tinybench": "^2.3.1",
"tinypool": "^0.3.0",
@@ -135,9 +138,11 @@
"diff": "^5.1.0",
"event-target-polyfill": "^0.0.3",
"execa": "^6.1.0",
+ "expect-type": "^0.15.0",
"fast-glob": "^3.2.12",
"find-up": "^6.3.0",
"flatted": "^3.2.7",
+ "get-tsconfig": "^4.2.0",
"happy-dom": "^7.6.6",
"jsdom": "^20.0.2",
"log-update": "^5.0.1",
diff --git a/packages/vitest/src/constants.ts b/packages/vitest/src/constants.ts
index 5201b877a72b..548c8880eb86 100644
--- a/packages/vitest/src/constants.ts
+++ b/packages/vitest/src/constants.ts
@@ -37,6 +37,9 @@ export const globalApis = [
'chai',
'expect',
'assert',
+ // typecheck
+ 'expectTypeOf',
+ 'assertType',
// utils
'vitest',
'vi',
diff --git a/packages/vitest/src/defaults.ts b/packages/vitest/src/defaults.ts
index 597ade0dc909..dd84c7a1438d 100644
--- a/packages/vitest/src/defaults.ts
+++ b/packages/vitest/src/defaults.ts
@@ -87,6 +87,11 @@ const config = {
fakeTimers: fakeTimersDefaults,
maxConcurrency: 5,
dangerouslyIgnoreUnhandledErrors: false,
+ typecheck: {
+ checker: 'tsc' as const,
+ include: ['**/*.{test,spec}-d.{ts,js}'],
+ exclude: defaultExclude,
+ },
}
export const configDefaults: Required> = Object.freeze(config)
diff --git a/packages/vitest/src/node/cli-api.ts b/packages/vitest/src/node/cli-api.ts
index 184c6ed7d60c..d06c0e9257d5 100644
--- a/packages/vitest/src/node/cli-api.ts
+++ b/packages/vitest/src/node/cli-api.ts
@@ -48,7 +48,7 @@ export async function startVitest(
const ctx = await createVitest(mode, options, viteOverrides)
- if (mode !== 'benchmark' && ctx.config.coverage.enabled) {
+ if (mode === 'test' && ctx.config.coverage.enabled) {
const provider = ctx.config.coverage.provider || 'c8'
if (typeof provider === 'string') {
const requiredPackages = CoverageProviderMap[provider]
diff --git a/packages/vitest/src/node/cli.ts b/packages/vitest/src/node/cli.ts
index c9e3cd7ec1e7..7d2edb7e9d33 100644
--- a/packages/vitest/src/node/cli.ts
+++ b/packages/vitest/src/node/cli.ts
@@ -66,6 +66,10 @@ cli
.command('bench [...filters]')
.action(benchmark)
+cli
+ .command('typecheck [...filters]')
+ .action(typecheck)
+
cli
.command('[...filters]')
.action((filters, options) => start('test', filters, options))
@@ -93,6 +97,11 @@ async function benchmark(cliFilters: string[], options: CliOptions): Promise {
+ await this.report('onCollected', files)
+ if (!files.length)
+ this.logger.printNoTestFound()
+ else
+ await this.report('onFinished', files)
+ if (sourceErrors.length && !this.config.typecheck.ignoreSourceErrors) {
+ process.exitCode = 1
+ await this.logger.printSourceTypeErrors(sourceErrors)
+ }
+ // if there are source errors, we are showing it, and then terminating process
+ if (!files.length) {
+ const exitCode = this.config.passWithNoTests ? (process.exitCode ?? 0) : 1
+ process.exit(exitCode)
+ }
+ if (this.config.watch) {
+ await this.report('onWatcherStart', files, [
+ ...sourceErrors,
+ ...this.state.getUnhandledErrors(),
+ ])
+ }
+ })
+ checker.onParseStart(async () => {
+ await this.report('onInit', this)
+ await this.report('onCollected', checker.getTestFiles())
+ })
+ checker.onWatcherRerun(async () => {
+ await this.report('onWatcherRerun', testsFilesList, 'File change detected. Triggering rerun.')
+ await checker.collectTests()
+ await this.report('onCollected', checker.getTestFiles())
+ })
+ await checker.collectTests()
+ await checker.start()
+ }
+
async start(filters?: string[]) {
+ if (this.mode === 'typecheck') {
+ await this.typecheck(filters)
+ return
+ }
+
try {
await this.initCoverageProvider()
await this.coverageProvider?.clean(this.config.coverage.clean)
@@ -470,6 +516,7 @@ export class Vitest {
this.closingPromise = Promise.allSettled([
this.pool?.close(),
this.server.close(),
+ this.typechecker?.stop(),
].filter(Boolean)).then((results) => {
results.filter(r => r.status === 'rejected').forEach((err) => {
this.logger.error('error during close', (err as PromiseRejectedResult).reason)
diff --git a/packages/vitest/src/node/error.ts b/packages/vitest/src/node/error.ts
index 79372aba3810..cb06ed529dc6 100644
--- a/packages/vitest/src/node/error.ts
+++ b/packages/vitest/src/node/error.ts
@@ -7,6 +7,7 @@ import type { ErrorWithDiff, ParsedStack, Position } from '../types'
import { lineSplitRE, parseStacktrace, posToNumber } from '../utils/source-map'
import { F_POINTER } from '../utils/figures'
import { stringify } from '../integrations/chai/jest-matcher-utils'
+import { TypeCheckError } from '../typecheck/typechecker'
import type { Vitest } from './core'
import { type DiffOptions, unifiedDiff } from './diff'
import { divider } from './reporters/renderers/utils'
@@ -45,18 +46,22 @@ export async function printError(error: unknown, ctx: Vitest, options: PrintErro
const stacks = parseStacktrace(e, fullStack)
- const nearest = stacks.find(stack =>
- ctx.server.moduleGraph.getModuleById(stack.file)
+ const nearest = error instanceof TypeCheckError
+ ? error.stacks[0]
+ : stacks.find(stack =>
+ ctx.server.moduleGraph.getModuleById(stack.file)
&& existsSync(stack.file),
- )
+ )
const errorProperties = getErrorProperties(e)
if (type)
printErrorType(type, ctx)
printErrorMessage(e, ctx.logger)
+
+ // if the error provide the frame
if (e.frame) {
- ctx.logger.log(c.yellow(e.frame))
+ ctx.logger.error(c.yellow(e.frame))
}
else {
printStack(ctx, stacks, nearest, errorProperties, (s, pos) => {
@@ -64,9 +69,9 @@ export async function printError(error: unknown, ctx: Vitest, options: PrintErro
const file = fileFromParsedStack(nearest)
// could point to non-existing original file
// for example, when there is a source map file, but no source in node_modules
- if (existsSync(file)) {
+ if (nearest.file === file || existsSync(file)) {
const sourceCode = readFileSync(file, 'utf-8')
- ctx.logger.log(c.yellow(generateCodeFrame(sourceCode, 4, pos)))
+ ctx.logger.error(c.yellow(generateCodeFrame(sourceCode, 4, pos)))
}
}
})
@@ -182,19 +187,19 @@ function printStack(
const file = fileFromParsedStack(frame)
const path = relative(ctx.config.root, file)
- logger.log(color(` ${c.dim(F_POINTER)} ${[frame.method, c.dim(`${path}:${pos.line}:${pos.column}`)].filter(Boolean).join(' ')}`))
+ logger.error(color(` ${c.dim(F_POINTER)} ${[frame.method, c.dim(`${path}:${pos.line}:${pos.column}`)].filter(Boolean).join(' ')}`))
onStack?.(frame, pos)
// reached at test file, skip the follow stack
if (frame.file in ctx.state.filesMap)
break
}
- logger.log()
+ logger.error()
const hasProperties = Object.keys(errorProperties).length > 0
if (hasProperties) {
- logger.log(c.red(c.dim(divider())))
+ logger.error(c.red(c.dim(divider())))
const propertiesString = stringify(errorProperties, 10, { printBasicPrototype: false })
- logger.log(c.red(c.bold('Serialized Error:')), c.gray(propertiesString))
+ logger.error(c.red(c.bold('Serialized Error:')), c.gray(propertiesString))
}
}
diff --git a/packages/vitest/src/node/logger.ts b/packages/vitest/src/node/logger.ts
index e6a6c6513b9b..9c2d2eae3264 100644
--- a/packages/vitest/src/node/logger.ts
+++ b/packages/vitest/src/node/logger.ts
@@ -2,6 +2,7 @@ import { createLogUpdate } from 'log-update'
import c from 'picocolors'
import { version } from '../../../../package.json'
import type { ErrorWithDiff } from '../types'
+import type { TypeCheckError } from '../typecheck/typechecker'
import { divider } from './reporters/renderers/utils'
import type { Vitest } from './core'
import { printError } from './error'
@@ -129,4 +130,16 @@ export class Logger {
}))
this.log(c.red(divider()))
}
+
+ async printSourceTypeErrors(errors: TypeCheckError[]) {
+ const errorMessage = c.red(c.bold(
+ `\nVitest found ${errors.length} error${errors.length > 1 ? 's' : ''} not related to your test files.`,
+ ))
+ this.log(c.red(divider(c.bold(c.inverse(' Source Errors ')))))
+ this.log(errorMessage)
+ await Promise.all(errors.map(async (err) => {
+ await this.printError(err, true)
+ }))
+ this.log(c.red(divider()))
+ }
}
diff --git a/packages/vitest/src/node/plugins/mock.ts b/packages/vitest/src/node/plugins/mock.ts
index 1267ac548fee..c41c7c65c420 100644
--- a/packages/vitest/src/node/plugins/mock.ts
+++ b/packages/vitest/src/node/plugins/mock.ts
@@ -125,7 +125,7 @@ function getIndexStatus(code: string, from: number) {
}
}
- beforeChar = code[index]
+ beforeChar = char
index++
}
diff --git a/packages/vitest/src/node/reporters/base.ts b/packages/vitest/src/node/reporters/base.ts
index 135b9ba464c6..624ff3bd6fb5 100644
--- a/packages/vitest/src/node/reporters/base.ts
+++ b/packages/vitest/src/node/reporters/base.ts
@@ -1,7 +1,7 @@
import { performance } from 'perf_hooks'
import c from 'picocolors'
import type { ErrorWithDiff, File, Reporter, Task, TaskResultPack, UserConsoleLog } from '../../types'
-import { clearInterval, getFullName, getSuites, getTests, hasFailed, hasFailedSnapshot, isNode, relativePath, setInterval } from '../../utils'
+import { clearInterval, getFullName, getSuites, getTests, getTypecheckTests, hasFailed, hasFailedSnapshot, isNode, relativePath, setInterval } from '../../utils'
import type { Vitest } from '../../node'
import { F_RIGHT } from '../../utils/figures'
import { divider, formatTimeString, getStateString, getStateSymbol, pointer, renderSnapshotSummary } from './renderers/utils'
@@ -55,7 +55,7 @@ export abstract class BaseReporter implements Reporter {
if (errors.length) {
if (!this.ctx.config.dangerouslyIgnoreUnhandledErrors)
process.exitCode = 1
- this.ctx.logger.printUnhandledErrors(errors)
+ await this.ctx.logger.printUnhandledErrors(errors)
}
}
@@ -93,11 +93,9 @@ export abstract class BaseReporter implements Reporter {
}
}
- async onWatcherStart() {
+ async onWatcherStart(files = this.ctx.state.getFiles(), errors = this.ctx.state.getUnhandledErrors()) {
this.resetLastRunLog()
- const files = this.ctx.state.getFiles()
- const errors = this.ctx.state.getUnhandledErrors()
const failed = errors.length > 0 || hasFailed(files)
const failedSnap = hasFailedSnapshot(files)
if (failed)
@@ -105,7 +103,10 @@ export abstract class BaseReporter implements Reporter {
else
this.ctx.logger.log(WAIT_FOR_CHANGE_PASS)
- const hints = [HELP_HINT]
+ const hints = []
+ // TODO typecheck doesn't support these for now
+ if (this.mode !== 'typecheck')
+ hints.push(HELP_HINT)
if (failedSnap)
hints.unshift(HELP_UPDATE_SNAP)
else
@@ -201,7 +202,7 @@ export abstract class BaseReporter implements Reporter {
}
async reportTestSummary(files: File[]) {
- const tests = getTests(files)
+ const tests = this.mode === 'typecheck' ? getTypecheckTests(files) : getTests(files)
const logger = this.ctx.logger
const executionTime = this.end - this.start
@@ -211,7 +212,7 @@ export abstract class BaseReporter implements Reporter {
const transformTime = Array.from(this.ctx.vitenode.fetchCache.values()).reduce((a, b) => a + (b?.duration || 0), 0)
const threadTime = collectTime + testsTime + setupTime
- const padTitle = (str: string) => c.dim(`${str.padStart(10)} `)
+ const padTitle = (str: string) => c.dim(`${str.padStart(11)} `)
const time = (time: number) => {
if (time > 1000)
return `${(time / 1000).toFixed(2)}s`
@@ -238,9 +239,16 @@ export abstract class BaseReporter implements Reporter {
logger.log(padTitle('Test Files'), getStateString(files))
logger.log(padTitle('Tests'), getStateString(tests))
+ if (this.mode === 'typecheck') {
+ // has only failed checks
+ const typechecks = getTests(files).filter(t => t.type === 'typecheck')
+ logger.log(padTitle('Type Errors'), getStateString(typechecks, 'errors', false))
+ }
logger.log(padTitle('Start at'), formatTimeString(this._timeStart))
if (this.watchFilters)
logger.log(padTitle('Duration'), time(threadTime))
+ else if (this.mode === 'typecheck')
+ logger.log(padTitle('Duration'), time(executionTime))
else
logger.log(padTitle('Duration'), time(executionTime) + c.dim(` (transform ${time(transformTime)}, setup ${time(setupTime)}, collect ${time(collectTime)}, tests ${time(testsTime)})`))
@@ -267,7 +275,8 @@ export abstract class BaseReporter implements Reporter {
}
if (failedTests.length) {
- logger.error(c.red(divider(c.bold(c.inverse(` Failed Tests ${failedTests.length} `)))))
+ const message = this.mode === 'typecheck' ? 'Type Errors' : 'Failed Tests'
+ logger.error(c.red(divider(c.bold(c.inverse(` ${message} ${failedTests.length} `)))))
logger.error()
await this.printTaskErrors(failedTests, errorDivider)
@@ -284,6 +293,8 @@ export abstract class BaseReporter implements Reporter {
logger.log(`\n${c.cyan(c.inverse(c.bold(' BENCH ')))} ${c.cyan('Summary')}\n`)
for (const bench of topBenchs) {
const group = bench.suite
+ if (!group)
+ continue
const groupName = getFullName(group)
logger.log(` ${bench.name}${c.dim(` - ${groupName}`)}`)
const siblings = group.tasks
diff --git a/packages/vitest/src/node/reporters/benchmark/json.ts b/packages/vitest/src/node/reporters/benchmark/json.ts
index 7f9af4376e0d..35eeaf0a0322 100644
--- a/packages/vitest/src/node/reporters/benchmark/json.ts
+++ b/packages/vitest/src/node/reporters/benchmark/json.ts
@@ -34,7 +34,7 @@ export class JsonReporter implements Reporter {
continue
if (!outputFile)
res.samples = 'ignore on terminal' as any
- testResults[test.suite.name] = (testResults[test.suite.name] || []).concat(res)
+ testResults[test.suite!.name] = (testResults[test.suite!.name] || []).concat(res)
}
if (tests.some(t => t.result?.state === 'run')) {
diff --git a/packages/vitest/src/node/reporters/default.ts b/packages/vitest/src/node/reporters/default.ts
index 403610916197..1a2fa9b93bf0 100644
--- a/packages/vitest/src/node/reporters/default.ts
+++ b/packages/vitest/src/node/reporters/default.ts
@@ -1,5 +1,5 @@
import c from 'picocolors'
-import type { UserConsoleLog } from '../../types'
+import type { File, UserConsoleLog } from '../../types'
import { BaseReporter } from './base'
import type { ListRendererOptions } from './renderers/listRenderer'
import { createListRenderer } from './renderers/listRenderer'
@@ -18,11 +18,13 @@ export class DefaultReporter extends BaseReporter {
super.onWatcherStart()
}
- onCollected() {
+ onCollected(files?: File[]) {
if (this.isTTY) {
this.rendererOptions.logger = this.ctx.logger
this.rendererOptions.showHeap = this.ctx.config.logHeapUsage
- const files = this.ctx.state.getFiles(this.watchFilters)
+ this.rendererOptions.mode = this.mode
+ if (!files)
+ files = this.ctx.state.getFiles(this.watchFilters)
if (!this.renderer)
this.renderer = createListRenderer(files, this.rendererOptions).start()
else
@@ -36,9 +38,9 @@ export class DefaultReporter extends BaseReporter {
await super.onFinished(files, errors)
}
- async onWatcherStart() {
+ async onWatcherStart(files = this.ctx.state.getFiles(), errors = this.ctx.state.getUnhandledErrors()) {
await this.stopListRender()
- await super.onWatcherStart()
+ await super.onWatcherStart(files, errors)
}
async stopListRender() {
diff --git a/packages/vitest/src/node/reporters/renderers/listRenderer.ts b/packages/vitest/src/node/reporters/renderers/listRenderer.ts
index ec4c2593a9a0..d1e94013ea94 100644
--- a/packages/vitest/src/node/reporters/renderers/listRenderer.ts
+++ b/packages/vitest/src/node/reporters/renderers/listRenderer.ts
@@ -1,8 +1,8 @@
import c from 'picocolors'
import cliTruncate from 'cli-truncate'
import stripAnsi from 'strip-ansi'
-import type { Benchmark, BenchmarkResult, SuiteHooks, Task } from '../../../types'
-import { clearInterval, getTests, notNullish, setInterval } from '../../../utils'
+import type { Benchmark, BenchmarkResult, SuiteHooks, Task, VitestRunMode } from '../../../types'
+import { clearInterval, getTests, getTypecheckTests, isTypecheckTest, notNullish, setInterval } from '../../../utils'
import { F_RIGHT } from '../../../utils/figures'
import type { Logger } from '../../logger'
import { getCols, getHookStateSymbol, getStateSymbol } from './utils'
@@ -11,6 +11,7 @@ export interface ListRendererOptions {
renderSucceed?: boolean
logger: Logger
showHeap: boolean
+ mode: VitestRunMode
}
const DURATION_LONG = 300
@@ -95,8 +96,10 @@ export function renderTree(tasks: Task[], options: ListRendererOptions, level =
if (task.type === 'test' && task.result?.retryCount && task.result.retryCount > 1)
suffix += c.yellow(` (retry x${task.result.retryCount})`)
- if (task.type === 'suite')
- suffix += c.dim(` (${getTests(task).length})`)
+ if (task.type === 'suite' && !isTypecheckTest(task)) {
+ const tests = options.mode === 'typecheck' ? getTypecheckTests(task) : getTests(task)
+ suffix += c.dim(` (${tests.length})`)
+ }
if (task.mode === 'skip' || task.mode === 'todo')
suffix += ` ${c.dim(c.gray('[skipped]'))}`
diff --git a/packages/vitest/src/node/reporters/renderers/utils.ts b/packages/vitest/src/node/reporters/renderers/utils.ts
index 469e37dfe666..39f0cbf9c784 100644
--- a/packages/vitest/src/node/reporters/renderers/utils.ts
+++ b/packages/vitest/src/node/reporters/renderers/utils.ts
@@ -91,7 +91,7 @@ export function renderSnapshotSummary(rootDir: string, snapshots: SnapshotSummar
return summary
}
-export function getStateString(tasks: Task[], name = 'tests') {
+export function getStateString(tasks: Task[], name = 'tests', showTotal = true) {
if (tasks.length === 0)
return c.dim(`no ${name}`)
@@ -105,7 +105,7 @@ export function getStateString(tasks: Task[], name = 'tests') {
passed.length ? c.bold(c.green(`${passed.length} passed`)) : null,
skipped.length ? c.yellow(`${skipped.length} skipped`) : null,
todo.length ? c.gray(`${todo.length} todo`) : null,
- ].filter(Boolean).join(c.dim(' | ')) + c.gray(` (${tasks.length})`)
+ ].filter(Boolean).join(c.dim(' | ')) + (showTotal ? c.gray(` (${tasks.length})`) : '')
}
export function getStateSymbol(task: Task) {
diff --git a/packages/vitest/src/node/stdin.ts b/packages/vitest/src/node/stdin.ts
index b4bd5e3d7d5f..667157fe76da 100644
--- a/packages/vitest/src/node/stdin.ts
+++ b/packages/vitest/src/node/stdin.ts
@@ -36,6 +36,14 @@ export function registerConsoleShortcuts(ctx: Vitest) {
const name = key?.name
+ // quit
+ if (name === 'q')
+ return ctx.exit(true)
+
+ // TODO typechecking doesn't support shortcuts this yet
+ if (ctx.mode === 'typecheck')
+ return
+
// help
if (name === 'h')
return printShortcutsHelp()
@@ -54,9 +62,6 @@ export function registerConsoleShortcuts(ctx: Vitest) {
// change fileNamePattern
if (name === 'p')
return inputFilePattern()
- // quit
- if (name === 'q')
- return ctx.exit(true)
}
async function keypressHandler(str: string, key: any) {
diff --git a/packages/vitest/src/runtime/collect.ts b/packages/vitest/src/runtime/collect.ts
index 1c18abd6aaf3..46b7d9fd5dac 100644
--- a/packages/vitest/src/runtime/collect.ts
+++ b/packages/vitest/src/runtime/collect.ts
@@ -1,5 +1,6 @@
-import type { File, ResolvedConfig, Suite, TaskBase } from '../types'
+import type { File, ResolvedConfig, Suite } from '../types'
import { getWorkerState, isBrowser, relativePath } from '../utils'
+import { interpretTaskModes, someTasksAreOnly } from '../utils/collect'
import { clearCollectorContext, defaultSuite } from './suite'
import { getHooks, setHooks } from './map'
import { processError } from './error'
@@ -99,75 +100,6 @@ export async function collectTests(paths: string[], config: ResolvedConfig): Pro
return files
}
-/**
- * If any tasks been marked as `only`, mark all other tasks as `skip`.
- */
-function interpretTaskModes(suite: Suite, namePattern?: string | RegExp, onlyMode?: boolean, parentIsOnly?: boolean, allowOnly?: boolean) {
- const suiteIsOnly = parentIsOnly || suite.mode === 'only'
-
- suite.tasks.forEach((t) => {
- // Check if either the parent suite or the task itself are marked as included
- const includeTask = suiteIsOnly || t.mode === 'only'
- if (onlyMode) {
- if (t.type === 'suite' && (includeTask || someTasksAreOnly(t))) {
- // Don't skip this suite
- if (t.mode === 'only') {
- checkAllowOnly(t, allowOnly)
- t.mode = 'run'
- }
- }
- else if (t.mode === 'run' && !includeTask) { t.mode = 'skip' }
- else if (t.mode === 'only') {
- checkAllowOnly(t, allowOnly)
- t.mode = 'run'
- }
- }
- if (t.type === 'test') {
- if (namePattern && !getTaskFullName(t).match(namePattern))
- t.mode = 'skip'
- }
- else if (t.type === 'suite') {
- if (t.mode === 'skip')
- skipAllTasks(t)
- else
- interpretTaskModes(t, namePattern, onlyMode, includeTask, allowOnly)
- }
- })
-
- // if all subtasks are skipped, mark as skip
- if (suite.mode === 'run') {
- if (suite.tasks.length && suite.tasks.every(i => i.mode !== 'run'))
- suite.mode = 'skip'
- }
-}
-
-function getTaskFullName(task: TaskBase): string {
- return `${task.suite ? `${getTaskFullName(task.suite)} ` : ''}${task.name}`
-}
-
-function someTasksAreOnly(suite: Suite): boolean {
- return suite.tasks.some(t => t.mode === 'only' || (t.type === 'suite' && someTasksAreOnly(t)))
-}
-
-function skipAllTasks(suite: Suite) {
- suite.tasks.forEach((t) => {
- if (t.mode === 'run') {
- t.mode = 'skip'
- if (t.type === 'suite')
- skipAllTasks(t)
- }
- })
-}
-
-function checkAllowOnly(task: TaskBase, allowOnly?: boolean) {
- if (allowOnly)
- return
- task.result = {
- state: 'fail',
- error: processError(new Error('[Vitest] Unexpected .only modifier. Remove it or pass --allowOnly argument to bypass this error')),
- }
-}
-
function calculateHash(parent: Suite) {
parent.tasks.forEach((t, idx) => {
t.id = `${parent.id}_${idx}`
diff --git a/packages/vitest/src/typecheck/assertType.ts b/packages/vitest/src/typecheck/assertType.ts
new file mode 100644
index 000000000000..b588f7a6ce9f
--- /dev/null
+++ b/packages/vitest/src/typecheck/assertType.ts
@@ -0,0 +1,7 @@
+const noop = () => {}
+
+export interface AssertType {
+ (value: T): void
+}
+
+export const assertType: AssertType = noop
diff --git a/packages/vitest/src/typecheck/collect.ts b/packages/vitest/src/typecheck/collect.ts
new file mode 100644
index 000000000000..9634bfb4a85a
--- /dev/null
+++ b/packages/vitest/src/typecheck/collect.ts
@@ -0,0 +1,142 @@
+import { relative } from 'pathe'
+import { parse as parseAst } from 'acorn'
+import { ancestor as walkAst } from 'acorn-walk'
+import type { RawSourceMap } from 'vite-node'
+
+import type { File, Suite, Vitest } from '../types'
+import { interpretTaskModes, someTasksAreOnly } from '../utils/collect'
+import { TYPECHECK_SUITE } from './constants'
+
+interface ParsedFile extends File {
+ start: number
+ end: number
+}
+
+interface ParsedSuite extends Suite {
+ start: number
+ end: number
+}
+
+interface LocalCallDefinition {
+ start: number
+ end: number
+ name: string
+ type: string
+ mode: 'run' | 'skip' | 'only' | 'todo'
+ task: ParsedSuite | ParsedFile
+}
+
+export interface FileInformation {
+ file: ParsedFile
+ filepath: string
+ parsed: string
+ map: RawSourceMap | null
+ definitions: LocalCallDefinition[]
+}
+
+export async function collectTests(ctx: Vitest, filepath: string): Promise {
+ const request = await ctx.vitenode.transformRequest(filepath)
+ if (!request)
+ return null
+ const ast = parseAst(request.code, {
+ ecmaVersion: 'latest',
+ allowAwaitOutsideFunction: true,
+ })
+ const file: ParsedFile = {
+ filepath,
+ type: 'suite',
+ id: '-1',
+ name: relative(ctx.config.root, filepath),
+ mode: 'run',
+ tasks: [],
+ start: ast.start,
+ end: ast.end,
+ result: {
+ state: 'pass',
+ },
+ }
+ const definitions: LocalCallDefinition[] = []
+ const getName = (callee: any): string | null => {
+ if (!callee)
+ return null
+ if (callee.type === 'Identifier')
+ return callee.name
+ if (callee.type === 'MemberExpression') {
+ // direct call as `__vite_ssr_exports_0__.test()`
+ if (callee.object?.name?.startsWith('__vite_ssr_'))
+ return getName(callee.property)
+ // call as `__vite_ssr__.test.skip()`
+ return getName(callee.object?.property)
+ }
+ return null
+ }
+ walkAst(ast, {
+ CallExpression(node) {
+ const { callee } = node as any
+ const name = getName(callee)
+ if (!name)
+ return
+ if (!['it', 'test', 'describe', 'suite'].includes(name))
+ return
+ const { arguments: [{ value: message }] } = node as any
+ const property = callee?.property?.name
+ const mode = !property || property === name ? 'run' : property
+ if (!['run', 'skip', 'todo', 'only'].includes(mode))
+ throw new Error(`${name}.${mode} syntax is not supported when testing types`)
+ definitions.push({
+ start: node.start,
+ end: node.end,
+ name: message,
+ type: name,
+ mode,
+ } as LocalCallDefinition)
+ },
+ })
+ let lastSuite: ParsedSuite = file
+ const updateLatestSuite = (index: number) => {
+ const suite = lastSuite
+ while (lastSuite !== file && lastSuite.end < index)
+ lastSuite = suite.suite as ParsedSuite
+ return lastSuite
+ }
+ definitions.sort((a, b) => a.start - b.start).forEach((definition, idx) => {
+ const latestSuite = updateLatestSuite(definition.start)
+ let mode = definition.mode
+ if (latestSuite.mode !== 'run') // inherit suite mode, if it's set
+ mode = latestSuite.mode
+ const state = mode === 'run' ? 'pass' : mode
+ // expectTypeOf and any type error is actually a "test" ("typecheck"),
+ // and all "test"s should be inside a "suite", so semantics inside typecheck for "test" changes
+ // if we ever allow having multiple errors in a test, we can change type to "test"
+ const task: ParsedSuite = {
+ type: 'suite',
+ id: idx.toString(),
+ suite: latestSuite,
+ file,
+ tasks: [],
+ mode,
+ name: definition.name,
+ end: definition.end,
+ start: definition.start,
+ result: {
+ state,
+ },
+ }
+ definition.task = task
+ latestSuite.tasks.push(task)
+ if (definition.type === 'describe' || definition.type === 'suite')
+ lastSuite = task
+ else
+ // to show correct amount of "tests" in summary, we mark this with a special symbol
+ Object.defineProperty(task, TYPECHECK_SUITE, { value: true })
+ })
+ const hasOnly = someTasksAreOnly(file)
+ interpretTaskModes(file, ctx.config.testNamePattern, hasOnly, false, ctx.config.allowOnly)
+ return {
+ file,
+ parsed: request.code,
+ filepath,
+ map: request.map as RawSourceMap | null,
+ definitions,
+ }
+}
diff --git a/packages/vitest/src/typecheck/constants.ts b/packages/vitest/src/typecheck/constants.ts
new file mode 100644
index 000000000000..c52d92249ff7
--- /dev/null
+++ b/packages/vitest/src/typecheck/constants.ts
@@ -0,0 +1,2 @@
+export const EXPECT_TYPEOF_MATCHERS = Symbol('vitest:expect-typeof-matchers')
+export const TYPECHECK_SUITE = Symbol('vitest:typecheck-suite')
diff --git a/packages/vitest/src/typecheck/expectTypeOf.ts b/packages/vitest/src/typecheck/expectTypeOf.ts
new file mode 100644
index 000000000000..a91a590dc4be
--- /dev/null
+++ b/packages/vitest/src/typecheck/expectTypeOf.ts
@@ -0,0 +1 @@
+export { expectTypeOf, type ExpectTypeOf } from 'expect-type'
diff --git a/packages/vitest/src/typecheck/parse.ts b/packages/vitest/src/typecheck/parse.ts
new file mode 100644
index 000000000000..34adb3137aae
--- /dev/null
+++ b/packages/vitest/src/typecheck/parse.ts
@@ -0,0 +1,126 @@
+import path from 'node:path'
+import url from 'node:url'
+import { writeFile } from 'node:fs/promises'
+import { getTsconfig } from 'get-tsconfig'
+import type { TypecheckConfig } from '../types'
+import type { RawErrsMap, TscErrorInfo } from './types'
+
+const __dirname = url.fileURLToPath(new URL('.', import.meta.url))
+const newLineRegExp = /\r?\n/
+const errCodeRegExp = /error TS(?\d+)/
+
+export async function makeTscErrorInfo(
+ errInfo: string,
+): Promise<[string, TscErrorInfo | null]> {
+ const [errFilePathPos = '', ...errMsgRawArr] = errInfo.split(':')
+ if (
+ !errFilePathPos
+ || errMsgRawArr.length === 0
+ || errMsgRawArr.join('').length === 0
+ )
+ return ['unknown filepath', null]
+
+ const errMsgRaw = errMsgRawArr.join('').trim()
+
+ // get filePath, line, col
+ const [errFilePath, errPos] = errFilePathPos
+ .slice(0, -1) // removes the ')'
+ .split('(')
+ if (!errFilePath || !errPos)
+ return ['unknown filepath', null]
+
+ const [errLine, errCol] = errPos.split(',')
+ if (!errLine || !errCol)
+ return [errFilePath, null]
+
+ // get errCode, errMsg
+ const execArr = errCodeRegExp.exec(errMsgRaw)
+ if (!execArr)
+ return [errFilePath, null]
+
+ const errCodeStr = execArr.groups?.errCode ?? ''
+ if (!errCodeStr)
+ return [errFilePath, null]
+
+ const line = Number(errLine)
+ const col = Number(errCol)
+ const errCode = Number(errCodeStr)
+ return [
+ errFilePath,
+ {
+ filePath: errFilePath,
+ errCode,
+ line,
+ column: col,
+ errMsg: errMsgRaw.slice(`error TS${errCode} `.length),
+ },
+ ]
+}
+
+export async function getTsconfigPath(root: string, config: TypecheckConfig) {
+ const tempConfigPath = path.join(root, 'tsconfig.temp.json')
+
+ const configName = config.tsconfig?.includes('jsconfig.json')
+ ? 'jsconfig.json'
+ : undefined
+
+ const tsconfig = getTsconfig(config.tsconfig || root, configName)
+
+ if (!tsconfig)
+ throw new Error('no tsconfig.json found')
+
+ try {
+ const tmpTsConfig: Record = { ...tsconfig.config }
+
+ tmpTsConfig.compilerOptions ??= {}
+ tmpTsConfig.compilerOptions.emitDeclarationOnly = false
+ tmpTsConfig.compilerOptions.incremental = true
+ tmpTsConfig.compilerOptions.tsBuildInfoFile = path.join(
+ __dirname,
+ 'tsconfig.tmp.tsbuildinfo',
+ )
+
+ const tsconfigFinalContent = JSON.stringify(tmpTsConfig, null, 2)
+ await writeFile(tempConfigPath, tsconfigFinalContent)
+ return tempConfigPath
+ }
+ catch (err) {
+ throw new Error('failed to write tsconfig.temp.json', { cause: err })
+ }
+}
+
+export async function getRawErrsMapFromTsCompile(
+ tscErrorStdout: string,
+) {
+ const rawErrsMap: RawErrsMap = new Map()
+
+ // Merge details line with main line (i.e. which contains file path)
+ const infos = await Promise.all(
+ tscErrorStdout
+ .split(newLineRegExp)
+ .reduce((prev, next) => {
+ if (!next)
+ return prev
+
+ else if (!next.startsWith(' '))
+ prev.push(next)
+
+ else
+ prev[prev.length - 1] += `\n${next}`
+
+ return prev
+ }, [])
+ .map(errInfoLine => makeTscErrorInfo(errInfoLine)),
+ )
+ infos.forEach(([errFilePath, errInfo]) => {
+ if (!errInfo)
+ return
+
+ if (!rawErrsMap.has(errFilePath))
+ rawErrsMap.set(errFilePath, [errInfo])
+
+ else
+ rawErrsMap.get(errFilePath)?.push(errInfo)
+ })
+ return rawErrsMap
+}
diff --git a/packages/vitest/src/typecheck/typechecker.ts b/packages/vitest/src/typecheck/typechecker.ts
new file mode 100644
index 000000000000..4a4508a8eedd
--- /dev/null
+++ b/packages/vitest/src/typecheck/typechecker.ts
@@ -0,0 +1,244 @@
+import { rm } from 'fs/promises'
+import type { ExecaChildProcess } from 'execa'
+import { execa } from 'execa'
+import { resolve } from 'pathe'
+import { SourceMapConsumer } from 'source-map'
+import { ensurePackageInstalled } from '../utils'
+import type { Awaitable, File, ParsedStack, Task, TscErrorInfo, Vitest } from '../types'
+import { getRawErrsMapFromTsCompile, getTsconfigPath } from './parse'
+import { createIndexMap } from './utils'
+import type { FileInformation } from './collect'
+import { collectTests } from './collect'
+
+export class TypeCheckError extends Error {
+ name = 'TypeCheckError'
+
+ constructor(public message: string, public stacks: ParsedStack[]) {
+ super(message)
+ }
+}
+
+interface ErrorsCache {
+ files: File[]
+ sourceErrors: TypeCheckError[]
+}
+
+type Callback = []> = (...args: Args) => Awaitable
+
+export class Typechecker {
+ private _onParseStart?: Callback
+ private _onParseEnd?: Callback<[ErrorsCache]>
+ private _onWatcherRerun?: Callback
+ private _result: ErrorsCache = {
+ files: [],
+ sourceErrors: [],
+ }
+
+ private _tests: Record | null = {}
+ private tempConfigPath?: string
+ private process!: ExecaChildProcess
+
+ constructor(protected ctx: Vitest, protected files: string[]) {}
+
+ public onParseStart(fn: Callback) {
+ this._onParseStart = fn
+ }
+
+ public onParseEnd(fn: Callback<[ErrorsCache]>) {
+ this._onParseEnd = fn
+ }
+
+ public onWatcherRerun(fn: Callback) {
+ this._onWatcherRerun = fn
+ }
+
+ protected async collectFileTests(filepath: string): Promise {
+ return collectTests(this.ctx, filepath)
+ }
+
+ public async collectTests() {
+ const tests = (await Promise.all(
+ this.files.map(filepath => this.collectFileTests(filepath)),
+ )).reduce((acc, data) => {
+ if (!data)
+ return acc
+ acc[data.filepath] = data
+ return acc
+ }, {} as Record)
+ this._tests = tests
+ return tests
+ }
+
+ protected async prepareResults(output: string) {
+ const typeErrors = await this.parseTscLikeOutput(output)
+ const testFiles = new Set(this.files)
+
+ if (!this._tests)
+ this._tests = await this.collectTests()
+
+ const sourceErrors: TypeCheckError[] = []
+ const files: File[] = []
+
+ testFiles.forEach((path) => {
+ const { file, definitions, map, parsed } = this._tests![path]
+ const errors = typeErrors.get(path)
+ files.push(file)
+ if (!errors)
+ return
+ const sortedDefinitions = [...definitions.sort((a, b) => b.start - a.start)]
+ // has no map for ".js" files that use // @ts-check
+ const mapConsumer = map && new SourceMapConsumer(map)
+ const indexMap = createIndexMap(parsed)
+ const markFailed = (task: Task) => {
+ task.result = {
+ state: task.mode === 'run' || task.mode === 'only' ? 'fail' : task.mode,
+ }
+ if (task.suite)
+ markFailed(task.suite)
+ }
+ errors.forEach(({ error, originalError }, idx) => {
+ const originalPos = mapConsumer?.generatedPositionFor({
+ line: originalError.line,
+ column: originalError.column,
+ source: path,
+ }) || originalError
+ const index = indexMap.get(`${originalPos.line}:${originalPos.column}`)
+ const definition = (index != null && sortedDefinitions.find(def => def.start <= index && def.end >= index)) || file
+ const suite = 'task' in definition ? definition.task : definition
+ const state = suite.mode === 'run' || suite.mode === 'only' ? 'fail' : suite.mode
+ const task: Task = {
+ type: 'typecheck',
+ id: idx.toString(),
+ name: `error expect ${idx + 1}`, // TODO naming
+ mode: suite.mode,
+ file,
+ suite,
+ result: {
+ state,
+ error: state === 'fail' ? error : undefined,
+ },
+ }
+ if (state === 'fail')
+ markFailed(suite)
+ suite.tasks.push(task)
+ })
+ })
+
+ typeErrors.forEach((errors, path) => {
+ if (!testFiles.has(path))
+ sourceErrors.push(...errors.map(({ error }) => error))
+ })
+
+ return {
+ files,
+ sourceErrors,
+ }
+ }
+
+ protected async parseTscLikeOutput(output: string) {
+ const errorsMap = await getRawErrsMapFromTsCompile(output)
+ const typesErrors = new Map()
+ errorsMap.forEach((errors, path) => {
+ const filepath = resolve(this.ctx.config.root, path)
+ const suiteErrors = errors.map((info) => {
+ const limit = Error.stackTraceLimit
+ Error.stackTraceLimit = 0
+ const error = new TypeCheckError(info.errMsg, [
+ {
+ file: filepath,
+ line: info.line,
+ column: info.column,
+ method: '',
+ sourcePos: {
+ line: info.line,
+ column: info.column,
+ },
+ },
+ ])
+ Error.stackTraceLimit = limit
+ return {
+ originalError: info,
+ error,
+ }
+ })
+ typesErrors.set(filepath, suiteErrors)
+ })
+ return typesErrors
+ }
+
+ public async clear() {
+ if (this.tempConfigPath)
+ await rm(this.tempConfigPath, { force: true })
+ }
+
+ public async stop() {
+ await this.clear()
+ this.process?.kill()
+ }
+
+ protected async ensurePackageInstalled(root: string, checker: string) {
+ if (checker !== 'tsc' && checker !== 'vue-tsc')
+ return
+ const packageName = checker === 'tsc' ? 'typescript' : 'vue-tsc'
+ await ensurePackageInstalled(packageName, root)
+ }
+
+ public async start() {
+ const { root, watch, typecheck } = this.ctx.config
+ await this.ensurePackageInstalled(root, typecheck.checker)
+
+ this.tempConfigPath = await getTsconfigPath(root, typecheck)
+ const args = ['--noEmit', '--pretty', 'false', '-p', this.tempConfigPath]
+ // use builtin watcher, because it's faster
+ if (watch)
+ args.push('--watch')
+ if (typecheck.allowJs)
+ args.push('--allowJs', '--checkJs')
+ let output = ''
+ const child = execa(typecheck.checker, args, {
+ cwd: root,
+ stdout: 'pipe',
+ reject: false,
+ })
+ this.process = child
+ await this._onParseStart?.()
+ let rerunTriggered = false
+ child.stdout?.on('data', (chunk) => {
+ output += chunk
+ if (!watch)
+ return
+ if (output.includes('File change detected') && !rerunTriggered) {
+ this._onWatcherRerun?.()
+ this._result.sourceErrors = []
+ this._result.files = []
+ this._tests = null // test structure migh've changed
+ rerunTriggered = true
+ }
+ if (/Found \w+ errors*. Watching for/.test(output)) {
+ rerunTriggered = false
+ this.prepareResults(output).then((result) => {
+ this._result = result
+ this._onParseEnd?.(result)
+ })
+ output = ''
+ }
+ })
+ if (!watch) {
+ await child
+ this._result = await this.prepareResults(output)
+ await this._onParseEnd?.(this._result)
+ await this.clear()
+ }
+ }
+
+ public getResult() {
+ return this._result
+ }
+
+ public getTestFiles() {
+ return Object.values(this._tests || {}).map(({ file }) => ({
+ ...file,
+ result: undefined,
+ }))
+ }
+}
diff --git a/packages/vitest/src/typecheck/types.ts b/packages/vitest/src/typecheck/types.ts
new file mode 100644
index 000000000000..0ba25f5f1139
--- /dev/null
+++ b/packages/vitest/src/typecheck/types.ts
@@ -0,0 +1,25 @@
+export type RawErrsMap = Map
+export interface TscErrorInfo {
+ filePath: string
+ errCode: number
+ errMsg: string
+ line: number
+ column: number
+}
+export interface CollectLineNumbers {
+ target: number
+ next: number
+ prev?: number
+}
+export type CollectLines = {
+ [key in keyof CollectLineNumbers]: string
+}
+export interface RootAndTarget {
+ root: string
+ targetAbsPath: string
+}
+export type Context = RootAndTarget & {
+ rawErrsMap: RawErrsMap
+ openedDirs: Set
+ lastActivePath?: string
+}
diff --git a/packages/vitest/src/typecheck/utils.ts b/packages/vitest/src/typecheck/utils.ts
new file mode 100644
index 000000000000..f947f6860d6e
--- /dev/null
+++ b/packages/vitest/src/typecheck/utils.ts
@@ -0,0 +1,17 @@
+export const createIndexMap = (source: string) => {
+ const map = new Map()
+ let index = 0
+ let line = 1
+ let column = 1
+ for (const char of source) {
+ map.set(`${line}:${column}`, index++)
+ if (char === '\n' || char === '\r\n') {
+ line++
+ column = 0
+ }
+ else {
+ column++
+ }
+ }
+ return map
+}
diff --git a/packages/vitest/src/types/config.ts b/packages/vitest/src/types/config.ts
index 933efc961e99..38df04792bbb 100644
--- a/packages/vitest/src/types/config.ts
+++ b/packages/vitest/src/types/config.ts
@@ -27,7 +27,7 @@ export interface EnvironmentOptions {
[x: string]: unknown
}
-export type VitestRunMode = 'test' | 'benchmark'
+export type VitestRunMode = 'test' | 'benchmark' | 'typecheck'
export interface InlineConfig {
/**
@@ -443,17 +443,46 @@ export interface InlineConfig {
* Ignore any unhandled errors that occur
*/
dangerouslyIgnoreUnhandledErrors?: boolean
+
+ /**
+ * Options for configuring typechecking test environment.
+ */
+ typecheck?: Partial
+}
+
+export interface TypecheckConfig {
+ /**
+ * What tools to use for type checking.
+ */
+ checker: 'tsc' | 'vue-tsc' | (string & Record)
+ /**
+ * Pattern for files that should be treated as test files
+ */
+ include: string[]
+ /**
+ * Pattern for files that should not be treated as test files
+ */
+ exclude: string[]
+ /**
+ * Check JS files that have `@ts-check` comment.
+ * If you have it enabled in tsconfig, this will not overwrite it.
+ */
+ allowJs?: boolean
+ /**
+ * Do not fail, if Vitest found errors outside the test files.
+ */
+ ignoreSourceErrors?: boolean
+ /**
+ * Path to tsconfig, relative to the project root.
+ */
+ tsconfig?: string
}
export interface UserConfig extends InlineConfig {
/**
* Path to the config file.
*
- * Default resolving to one of:
- * - `vitest.config.js`
- * - `vitest.config.ts`
- * - `vite.config.js`
- * - `vite.config.ts`
+ * Default resolving to `vitest.config.*`, `vite.config.*`
*/
config?: string | undefined
@@ -489,7 +518,7 @@ export interface UserConfig extends InlineConfig {
shard?: string
}
-export interface ResolvedConfig extends Omit, 'config' | 'filters' | 'coverage' | 'testNamePattern' | 'related' | 'api' | 'reporters' | 'resolveSnapshotPath' | 'benchmark' | 'shard' | 'cache' | 'sequence'> {
+export interface ResolvedConfig extends Omit, 'config' | 'filters' | 'coverage' | 'testNamePattern' | 'related' | 'api' | 'reporters' | 'resolveSnapshotPath' | 'benchmark' | 'shard' | 'cache' | 'sequence' | 'typecheck'> {
mode: VitestRunMode
base?: string
@@ -526,4 +555,6 @@ export interface ResolvedConfig extends Omit, 'config' | 'f
shuffle?: boolean
seed?: number
}
+
+ typecheck: TypecheckConfig
}
diff --git a/packages/vitest/src/types/index.ts b/packages/vitest/src/types/index.ts
index 5eaeef90cd0d..74bbd2b7b56d 100644
--- a/packages/vitest/src/types/index.ts
+++ b/packages/vitest/src/types/index.ts
@@ -1,6 +1,9 @@
import './vite'
import './global'
+export { expectTypeOf, type ExpectTypeOf } from '../typecheck/expectTypeOf'
+export { assertType, type AssertType } from '../typecheck/assertType'
+export * from '../typecheck/types'
export * from './config'
export * from './tasks'
export * from './reporter'
diff --git a/packages/vitest/src/types/reporter.ts b/packages/vitest/src/types/reporter.ts
index f2edcf31f65e..9eb6b2b1292a 100644
--- a/packages/vitest/src/types/reporter.ts
+++ b/packages/vitest/src/types/reporter.ts
@@ -10,7 +10,7 @@ export interface Reporter {
onTaskUpdate?: (packs: TaskResultPack[]) => Awaitable
onTestRemoved?: (trigger?: string) => Awaitable
- onWatcherStart?: () => Awaitable
+ onWatcherStart?: (files?: File[], errors?: unknown[]) => Awaitable
onWatcherRerun?: (files: string[], trigger?: string) => Awaitable
onServerRestart?: (reason?: string) => Awaitable
diff --git a/packages/vitest/src/types/tasks.ts b/packages/vitest/src/types/tasks.ts
index c4e426d84078..ba2497b42bc3 100644
--- a/packages/vitest/src/types/tasks.ts
+++ b/packages/vitest/src/types/tasks.ts
@@ -55,7 +55,11 @@ export interface Test extends TaskBase {
onFailed?: OnTestFailedHandler[]
}
-export type Task = Test | Suite | File | Benchmark
+export interface TypeCheck extends TaskBase {
+ type: 'typecheck'
+}
+
+export type Task = Test | Suite | File | Benchmark | TypeCheck
export type DoneCallback = (error?: any) => void
export type TestFunction = (context: TestContext & ExtraContext) => Awaitable | void
diff --git a/packages/vitest/src/utils/collect.ts b/packages/vitest/src/utils/collect.ts
new file mode 100644
index 000000000000..7c29ebe468c0
--- /dev/null
+++ b/packages/vitest/src/utils/collect.ts
@@ -0,0 +1,70 @@
+import type { Suite, TaskBase } from '../types'
+
+/**
+ * If any tasks been marked as `only`, mark all other tasks as `skip`.
+ */
+export function interpretTaskModes(suite: Suite, namePattern?: string | RegExp, onlyMode?: boolean, parentIsOnly?: boolean, allowOnly?: boolean) {
+ const suiteIsOnly = parentIsOnly || suite.mode === 'only'
+
+ suite.tasks.forEach((t) => {
+ // Check if either the parent suite or the task itself are marked as included
+ const includeTask = suiteIsOnly || t.mode === 'only'
+ if (onlyMode) {
+ if (t.type === 'suite' && (includeTask || someTasksAreOnly(t))) {
+ // Don't skip this suite
+ if (t.mode === 'only') {
+ checkAllowOnly(t, allowOnly)
+ t.mode = 'run'
+ }
+ }
+ else if (t.mode === 'run' && !includeTask) { t.mode = 'skip' }
+ else if (t.mode === 'only') {
+ checkAllowOnly(t, allowOnly)
+ t.mode = 'run'
+ }
+ }
+ if (t.type === 'test') {
+ if (namePattern && !getTaskFullName(t).match(namePattern))
+ t.mode = 'skip'
+ }
+ else if (t.type === 'suite') {
+ if (t.mode === 'skip')
+ skipAllTasks(t)
+ else
+ interpretTaskModes(t, namePattern, onlyMode, includeTask, allowOnly)
+ }
+ })
+
+ // if all subtasks are skipped, mark as skip
+ if (suite.mode === 'run') {
+ if (suite.tasks.length && suite.tasks.every(i => i.mode !== 'run'))
+ suite.mode = 'skip'
+ }
+}
+
+function getTaskFullName(task: TaskBase): string {
+ return `${task.suite ? `${getTaskFullName(task.suite)} ` : ''}${task.name}`
+}
+
+export function someTasksAreOnly(suite: Suite): boolean {
+ return suite.tasks.some(t => t.mode === 'only' || (t.type === 'suite' && someTasksAreOnly(t)))
+}
+
+function skipAllTasks(suite: Suite) {
+ suite.tasks.forEach((t) => {
+ if (t.mode === 'run') {
+ t.mode = 'skip'
+ if (t.type === 'suite')
+ skipAllTasks(t)
+ }
+ })
+}
+
+function checkAllowOnly(task: TaskBase, allowOnly?: boolean) {
+ if (allowOnly)
+ return
+ task.result = {
+ state: 'fail',
+ error: new Error('[Vitest] Unexpected .only modifier. Remove it or pass --allowOnly argument to bypass this error'),
+ }
+}
diff --git a/packages/vitest/src/utils/tasks.ts b/packages/vitest/src/utils/tasks.ts
index ee56ef0aac31..7384f65acb41 100644
--- a/packages/vitest/src/utils/tasks.ts
+++ b/packages/vitest/src/utils/tasks.ts
@@ -1,14 +1,27 @@
-import type { Arrayable, Benchmark, Suite, Task, Test } from '../types'
+import type { Arrayable, Benchmark, Suite, Task, Test, TypeCheck } from '../types'
+import { TYPECHECK_SUITE } from '../typecheck/constants'
import { toArray } from './base'
-function isAtomTest(s: Task): s is Test | Benchmark {
- return (s.type === 'test' || s.type === 'benchmark')
+function isAtomTest(s: Task): s is Test | Benchmark | TypeCheck {
+ return (s.type === 'test' || s.type === 'benchmark' || s.type === 'typecheck')
}
-export function getTests(suite: Arrayable): (Test | Benchmark)[] {
+export function getTests(suite: Arrayable): (Test | Benchmark | TypeCheck)[] {
return toArray(suite).flatMap(s => isAtomTest(s) ? [s] : s.tasks.flatMap(c => isAtomTest(c) ? [c] : getTests(c)))
}
+export function isTypecheckTest(suite: Task): suite is Suite {
+ return TYPECHECK_SUITE in suite
+}
+
+export function getTypecheckTests(suite: Arrayable): Suite[] {
+ return toArray(suite).flatMap((s) => {
+ if (s.type !== 'suite')
+ return []
+ return TYPECHECK_SUITE in s ? [s, ...getTypecheckTests(s.tasks)] : getTypecheckTests(s.tasks)
+ })
+}
+
export function getTasks(tasks: Arrayable = []): Task[] {
return toArray(tasks).flatMap(s => isAtomTest(s) ? [s] : [s, ...getTasks(s.tasks)])
}
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index cb8b6d5f1416..240b129946aa 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -748,6 +748,7 @@ importers:
packages/vite-node:
specifiers:
'@types/debug': ^4.1.7
+ '@types/source-map': ^0.5.7
'@types/source-map-support': ^0.5.6
cac: ^6.7.14
debug: ^4.3.4
@@ -755,16 +756,19 @@ importers:
pathe: ^0.2.0
picocolors: ^1.0.0
rollup: ^2.79.1
+ source-map: ^0.6.1
source-map-support: ^0.5.21
vite: ^3.2.3
dependencies:
debug: 4.3.4
mlly: 0.5.16
pathe: 0.2.0
+ source-map: 0.6.1
source-map-support: 0.5.21
vite: 3.2.3
devDependencies:
'@types/debug': 4.1.7
+ '@types/source-map': 0.5.7
'@types/source-map-support': 0.5.6
cac: 6.7.14
picocolors: 1.0.0
@@ -785,6 +789,8 @@ importers:
'@types/prompts': ^2.4.1
'@types/sinonjs__fake-timers': ^8.1.2
'@vitest/ui': workspace:*
+ acorn: ^8.8.0
+ acorn-walk: ^8.2.0
birpc: ^0.2.3
cac: ^6.7.14
chai: ^4.3.6
@@ -794,9 +800,11 @@ importers:
diff: ^5.1.0
event-target-polyfill: ^0.0.3
execa: ^6.1.0
+ expect-type: ^0.15.0
fast-glob: ^3.2.12
find-up: ^6.3.0
flatted: ^3.2.7
+ get-tsconfig: ^4.2.0
happy-dom: ^7.6.6
jsdom: ^20.0.2
local-pkg: ^0.4.2
@@ -812,6 +820,7 @@ importers:
pretty-format: ^27.5.1
prompts: ^2.4.2
rollup: ^2.79.1
+ source-map: ^0.6.1
strip-ansi: ^7.0.1
strip-literal: ^0.4.2
tinybench: ^2.3.1
@@ -825,9 +834,12 @@ importers:
'@types/chai': 4.3.3
'@types/chai-subset': 1.3.3
'@types/node': 18.7.13
+ acorn: 8.8.0
+ acorn-walk: 8.2.0
chai: 4.3.6
debug: 4.3.4
local-pkg: 0.4.2
+ source-map: 0.6.1
strip-literal: 0.4.2
tinybench: 2.3.1
tinypool: 0.3.0
@@ -851,9 +863,11 @@ importers:
diff: 5.1.0
event-target-polyfill: 0.0.3
execa: 6.1.0
+ expect-type: 0.15.0
fast-glob: 3.2.12
find-up: 6.3.0
flatted: 3.2.7
+ get-tsconfig: 4.2.0
happy-dom: 7.6.6
jsdom: 20.0.2
log-update: 5.0.1
@@ -1107,6 +1121,19 @@ importers:
execa: 6.1.0
vitest: link:../../packages/vitest
+ test/typescript:
+ specifiers:
+ execa: ^6.1.0
+ typescript: ^4.8.4
+ vitest: workspace:*
+ vue-tsc: ^0.40.13
+ dependencies:
+ vitest: link:../../packages/vitest
+ devDependencies:
+ execa: 6.1.0
+ typescript: 4.8.4
+ vue-tsc: 0.40.13_typescript@4.8.4
+
test/vite-config:
specifiers:
pathe: ^0.2.0
@@ -7203,6 +7230,13 @@ packages:
source-map: 0.6.1
dev: true
+ /@types/source-map/0.5.7:
+ resolution: {integrity: sha512-LrnsgZIfJaysFkv9rRJp4/uAyqw87oVed3s1hhF83nwbo9c7MG9g5DqR0seHP+lkX4ldmMrVolPjQSe2ZfD0yA==}
+ deprecated: This is a stub types definition for source-map (https://github.com/mozilla/source-map). source-map provides its own type definitions, so you don't need @types/source-map installed!
+ dependencies:
+ source-map: 0.7.4
+ dev: true
+
/@types/stack-utils/2.0.1:
resolution: {integrity: sha512-Hl219/BT5fLAaz6NDkSuhzasy49dwQS/DSdu4MdggFB8zcXv7vflBI3xp7FEmkmdDkBUI2bPUNeMttp2knYdxw==}
dev: true
@@ -7836,6 +7870,44 @@ packages:
vue: 2.7.10
dev: true
+ /@volar/code-gen/0.40.13:
+ resolution: {integrity: sha512-4gShBWuMce868OVvgyA1cU5WxHbjfEme18Tw6uVMfweZCF5fB2KECG0iPrA9D54vHk3FeHarODNwgIaaFfUBlA==}
+ dependencies:
+ '@volar/source-map': 0.40.13
+ dev: true
+
+ /@volar/source-map/0.40.13:
+ resolution: {integrity: sha512-dbdkAB2Nxb0wLjAY5O64o3ywVWlAGONnBIoKAkXSf6qkGZM+nJxcizsoiI66K+RHQG0XqlyvjDizfnTxr+6PWg==}
+ dependencies:
+ '@vue/reactivity': 3.2.38
+ dev: true
+
+ /@volar/typescript-faster/0.40.13:
+ resolution: {integrity: sha512-uy+TlcFkKoNlKEnxA4x5acxdxLyVDIXGSc8cYDNXpPKjBKXrQaetzCzlO3kVBqu1VLMxKNGJMTKn35mo+ILQmw==}
+ dependencies:
+ semver: 7.3.8
+ dev: true
+
+ /@volar/vue-language-core/0.40.13:
+ resolution: {integrity: sha512-QkCb8msi2KUitTdM6Y4kAb7/ZlEvuLcbBFOC2PLBlFuoZwyxvSP7c/dBGmKGtJlEvMX0LdCyrg5V2aBYxD38/Q==}
+ dependencies:
+ '@volar/code-gen': 0.40.13
+ '@volar/source-map': 0.40.13
+ '@vue/compiler-core': 3.2.41
+ '@vue/compiler-dom': 3.2.41
+ '@vue/compiler-sfc': 3.2.41
+ '@vue/reactivity': 3.2.41
+ '@vue/shared': 3.2.41
+ dev: true
+
+ /@volar/vue-typescript/0.40.13:
+ resolution: {integrity: sha512-o7bNztwjs8JmbQjVkrnbZUOfm7q4B8ZYssETISN1tRaBdun6cfNqgpkvDYd+VUBh1O4CdksvN+5BUNnwAz4oCQ==}
+ dependencies:
+ '@volar/code-gen': 0.40.13
+ '@volar/typescript-faster': 0.40.13
+ '@volar/vue-language-core': 0.40.13
+ dev: true
+
/@vue/babel-helper-vue-transform-on/1.0.2:
resolution: {integrity: sha512-hz4R8tS5jMn8lDq6iD+yWL6XNB699pGIVLk7WSJnn1dbpjaazsjZQkieJoRX6gW5zpYSCFqQ7jUquPNY65tQYA==}
dev: true
@@ -7954,6 +8026,12 @@ packages:
estree-walker: 2.0.2
magic-string: 0.25.9
+ /@vue/reactivity/3.2.38:
+ resolution: {integrity: sha512-6L4myYcH9HG2M25co7/BSo0skKFHpAN8PhkNPM4xRVkyGl1K5M3Jx4rp5bsYhvYze2K4+l+pioN4e6ZwFLUVtw==}
+ dependencies:
+ '@vue/shared': 3.2.38
+ dev: true
+
/@vue/reactivity/3.2.39:
resolution: {integrity: sha512-vlaYX2a3qMhIZfrw3Mtfd+BuU+TZmvDrPMa+6lpfzS9k/LnGxkSuf0fhkP0rMGfiOHPtyKoU9OJJJFGm92beVQ==}
dependencies:
@@ -8008,6 +8086,10 @@ packages:
'@vue/shared': 3.2.41
vue: 3.2.41
+ /@vue/shared/3.2.38:
+ resolution: {integrity: sha512-dTyhTIRmGXBjxJE+skC8tTWCGLCVc4wQgRRLt8+O9p5ewBAjoBwtCAkLPrtToSr1xltoe3st21Pv953aOZ7alg==}
+ dev: true
+
/@vue/shared/3.2.39:
resolution: {integrity: sha512-D3dl2ZB9qE6mTuWPk9RlhDeP1dgNRUKC3NJxji74A4yL8M2MwlhLKUC/49WHjrNzSPug58fWx/yFbaTzGAQSBw==}
@@ -8556,7 +8638,6 @@ packages:
/acorn-walk/8.2.0:
resolution: {integrity: sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==}
engines: {node: '>=0.4.0'}
- dev: true
/acorn/6.4.2:
resolution: {integrity: sha512-XtGIhXwF8YM8bJhGxG5kXgjkEuNGLTkoYqVE+KMR+aspr4KGYmKYg7yUe3KghyQ9yheNwLnjmzh/7+gfDBmHCQ==}
@@ -12349,6 +12430,10 @@ packages:
- supports-color
dev: true
+ /expect-type/0.15.0:
+ resolution: {integrity: sha512-yWnriYB4e8G54M5/fAFj7rCIBiKs1HAACaY13kCz6Ku0dezjS9aMcfcdVK2X8Tv2tEV1BPz/wKfQ7WA4S/d8aA==}
+ dev: true
+
/expect/29.0.1:
resolution: {integrity: sha512-yQgemsjLU+1S8t2A7pXT3Sn/v5/37LY8J+tocWtKEA0iEYYc6gfKbbJJX2fxHZmd7K9WpdbQqXUpmYkq1aewYg==}
engines: {node: ^14.15.0 || ^16.10.0 || >=18.0.0}
@@ -20742,6 +20827,17 @@ packages:
vue: 2.7.10
dev: true
+ /vue-tsc/0.40.13_typescript@4.8.4:
+ resolution: {integrity: sha512-xzuN3g5PnKfJcNrLv4+mAjteMd5wLm5fRhW0034OfNJZY4WhB07vhngea/XeGn7wNYt16r7syonzvW/54dcNiA==}
+ hasBin: true
+ peerDependencies:
+ typescript: '*'
+ dependencies:
+ '@volar/vue-language-core': 0.40.13
+ '@volar/vue-typescript': 0.40.13
+ typescript: 4.8.4
+ dev: true
+
/vue/2.7.10:
resolution: {integrity: sha512-HmFC70qarSHPXcKtW8U8fgIkF6JGvjEmDiVInTkKZP0gIlEPhlVlcJJLkdGIDiNkIeA2zJPQTWJUI4iWe+AVfg==}
dependencies:
diff --git a/test/stacktraces/test/__snapshots__/runner.test.ts.snap b/test/stacktraces/test/__snapshots__/runner.test.ts.snap
index 421a5591b00f..706d64998dc1 100644
--- a/test/stacktraces/test/__snapshots__/runner.test.ts.snap
+++ b/test/stacktraces/test/__snapshots__/runner.test.ts.snap
@@ -1,8 +1,8 @@
// Vitest Snapshot v1
exports[`stacktraces should pick error frame if present > frame.spec.imba > frame.spec.imba 1`] = `
-" ❯ frame.spec.imba (0 test)
-
+" FAIL frame.spec.imba [ frame.spec.imba ]
+imba-parser error: Unexpected 'CALL_END'
4 | test(\\"1+1\\") do
5 | expect(1+1).toBe 2
6 | frame.
diff --git a/test/stacktraces/test/runner.test.ts b/test/stacktraces/test/runner.test.ts
index 2e96047586e6..4c9254afa4c1 100644
--- a/test/stacktraces/test/runner.test.ts
+++ b/test/stacktraces/test/runner.test.ts
@@ -13,21 +13,19 @@ describe('stacktraces should respect sourcemaps', async () => {
if (process.platform === 'win32' && process.env.CI)
return
- let error: any
- await execa('npx', ['vitest', 'run', file], {
+ const { stderr } = await execa('npx', ['vitest', 'run', file], {
cwd: root,
+ reject: false,
+ stdio: 'pipe',
env: {
...process.env,
CI: 'true',
NO_COLOR: 'true',
},
})
- .catch((e) => {
- error = e
- })
- expect(error).toBeTruthy()
- const lines = String(error).split(/\n/g)
+ expect(stderr).toBeTruthy()
+ const lines = String(stderr).split(/\n/g)
const index = lines.findIndex(val => val.includes(`${file}:`))
const msg = lines.slice(index, index + 8).join('\n')
expect(msg).toMatchSnapshot(file)
@@ -45,22 +43,20 @@ describe('stacktraces should pick error frame if present', async () => {
if (process.platform === 'win32' && process.env.CI)
return
- let error: any
- await execa('npx', ['vitest', 'run', file], {
+ const { stderr } = await execa('npx', ['vitest', 'run', file], {
cwd: root,
+ reject: false,
+ stdio: 'pipe',
env: {
...process.env,
CI: 'true',
NO_COLOR: 'true',
},
})
- .catch((e) => {
- error = e
- })
- expect(error).toBeTruthy()
- const lines = String(error).split(/\n/g)
- const index = lines.findIndex(val => val.includes('(0 test)'))
+ expect(stderr).toBeTruthy()
+ const lines = String(stderr).split(/\n/g)
+ const index = lines.findIndex(val => val.includes('FAIL'))
const msg = lines.slice(index, index + 8).join('\n')
expect(msg).toMatchSnapshot(file)
}, 30000)
diff --git a/test/typescript/failing/expect-error.test-d.ts b/test/typescript/failing/expect-error.test-d.ts
new file mode 100644
index 000000000000..ba2277ca4a7f
--- /dev/null
+++ b/test/typescript/failing/expect-error.test-d.ts
@@ -0,0 +1,6 @@
+import { expectTypeOf, test } from 'vitest'
+
+test('failing test with expect-error', () => {
+ // @ts-expect-error expect nothing
+ expectTypeOf(1).toEqualTypeOf()
+})
diff --git a/test/typescript/failing/fail.test-d.ts b/test/typescript/failing/fail.test-d.ts
new file mode 100644
index 000000000000..3c0393858ca2
--- /dev/null
+++ b/test/typescript/failing/fail.test-d.ts
@@ -0,0 +1,16 @@
+import { describe, expectTypeOf, test } from 'vitest'
+
+test('failing test', () => {
+ expectTypeOf(1).toEqualTypeOf()
+})
+
+describe('nested suite', () => {
+ describe('nested 2', () => {
+ test('failing test 2', () => {
+ expectTypeOf(1).toBeVoid()
+ })
+ })
+
+ expectTypeOf(1).toBeVoid()
+})
+
diff --git a/test/typescript/failing/js-fail.test-d.js b/test/typescript/failing/js-fail.test-d.js
new file mode 100644
index 000000000000..e4f61e0f0df4
--- /dev/null
+++ b/test/typescript/failing/js-fail.test-d.js
@@ -0,0 +1,7 @@
+// @ts-check
+
+import { expectTypeOf, test } from 'vitest'
+
+test('js test fails', () => {
+ expectTypeOf(1).toBeArray()
+})
diff --git a/test/typescript/failing/only.test-d.ts b/test/typescript/failing/only.test-d.ts
new file mode 100644
index 000000000000..0fa60c9b0cc5
--- /dev/null
+++ b/test/typescript/failing/only.test-d.ts
@@ -0,0 +1,5 @@
+import { expectTypeOf, test } from 'vitest'
+
+test.only('failing test', () => {
+ expectTypeOf(1).toEqualTypeOf()
+})
diff --git a/test/typescript/package.json b/test/typescript/package.json
new file mode 100644
index 000000000000..7873d6655cd9
--- /dev/null
+++ b/test/typescript/package.json
@@ -0,0 +1,15 @@
+{
+ "scripts": {
+ "test": "vitest",
+ "types": "vitest typecheck --run",
+ "tsc": "tsc --watch --pretty false --noEmit"
+ },
+ "dependencies": {
+ "vitest": "workspace:*"
+ },
+ "devDependencies": {
+ "execa": "^6.1.0",
+ "typescript": "^4.8.4",
+ "vue-tsc": "^0.40.13"
+ }
+}
diff --git a/test/typescript/test-d/js.test-d.js b/test/typescript/test-d/js.test-d.js
new file mode 100644
index 000000000000..63697f27b4a6
--- /dev/null
+++ b/test/typescript/test-d/js.test-d.js
@@ -0,0 +1,7 @@
+// @ts-check
+
+import { expectTypeOf, test } from 'vitest'
+
+test('js test also works', () => {
+ expectTypeOf(1).toEqualTypeOf(2)
+})
diff --git a/test/typescript/test-d/test.test-d.ts b/test/typescript/test-d/test.test-d.ts
new file mode 100644
index 000000000000..dcbd61361c37
--- /dev/null
+++ b/test/typescript/test-d/test.test-d.ts
@@ -0,0 +1,38 @@
+/* eslint-disable @typescript-eslint/ban-ts-comment */
+import { describe, expectTypeOf, test } from 'vitest'
+
+describe('test', () => {
+ test('some-test', () => {
+ expectTypeOf(Date).toBeConstructibleWith(new Date())
+ expectTypeOf(Date).toBeConstructibleWith('01-01-2000')
+
+ type ResponsiveProp = T | T[] | { xs?: T; sm?: T; md?: T }
+ const getResponsiveProp = (_props: T): ResponsiveProp => ({})
+ interface CSSProperties { margin?: string; padding?: string }
+ const cssProperties: CSSProperties = { margin: '1px', padding: '2px' }
+ expectTypeOf(getResponsiveProp(cssProperties))
+ .exclude()
+ // .exclude<{ xs?: unknown }>()
+ .toEqualTypeOf()
+ })
+
+ describe('test2', () => {
+ test('some-test 2', () => {
+ expectTypeOf(Promise.resolve('string')).resolves.toEqualTypeOf()
+ expectTypeOf(45).toEqualTypeOf(45)
+ })
+ })
+
+ test('ignored error', () => {
+ // eslint-disable-next-line @typescript-eslint/prefer-ts-expect-error
+ // @ts-ignore
+ expectTypeOf(45).toEqualTypeOf()
+ })
+
+ test('expected error', () => {
+ // @ts-expect-error
+ expectTypeOf(45).toEqualTypeOf()
+ })
+})
+
+expectTypeOf({ wolk: 'true' }).toHaveProperty('wolk')
diff --git a/test/typescript/test/__snapshots__/runner.test.ts.snap b/test/typescript/test/__snapshots__/runner.test.ts.snap
new file mode 100644
index 000000000000..fedcd22e556b
--- /dev/null
+++ b/test/typescript/test/__snapshots__/runner.test.ts.snap
@@ -0,0 +1,54 @@
+// Vitest Snapshot v1
+
+exports[`should fails > typecheck files > expect-error.test-d.ts 1`] = `
+" ❯ expect-error.test-d.ts:4:3
+ 2|
+ 3| test('failing test with expect-error', () => {
+ 4| // @ts-expect-error expect nothing
+ | ^
+ 5| expectTypeOf(1).toEqualTypeOf()
+ 6| })
+"
+`;
+
+exports[`should fails > typecheck files > fail.test-d.ts 1`] = `
+" ❯ fail.test-d.ts:4:19
+ 2|
+ 3| test('failing test', () => {
+ 4| expectTypeOf(1).toEqualTypeOf()
+ | ^
+ 5| })
+ 6|
+"
+`;
+
+exports[`should fails > typecheck files > js-fail.test-d.js 1`] = `
+" ❯ js-fail.test-d.js:6:19
+ 4|
+ 5| test('js test fails', () => {
+ 6| expectTypeOf(1).toBeArray()
+ | ^
+ 7| })
+ 8|
+"
+`;
+
+exports[`should fails > typecheck files > only.test-d.ts 1`] = `
+" ❯ only.test-d.ts:4:19
+ 2|
+ 3| test.only('failing test', () => {
+ 4| expectTypeOf(1).toEqualTypeOf()
+ | ^
+ 5| })
+ 6|
+"
+`;
+
+exports[`should fails > typecheck files 1`] = `
+"TypeCheckError: Expected 1 arguments, but got 0.
+TypeCheckError: Expected 1 arguments, but got 0.
+TypeCheckError: Expected 1 arguments, but got 0.
+TypeCheckError: Expected 1 arguments, but got 0.
+TypeCheckError: Expected 1 arguments, but got 0.
+TypeCheckError: Unused '@ts-expect-error' directive."
+`;
diff --git a/test/typescript/test/runner.test.ts b/test/typescript/test/runner.test.ts
new file mode 100644
index 000000000000..31f5c3360f7f
--- /dev/null
+++ b/test/typescript/test/runner.test.ts
@@ -0,0 +1,48 @@
+import { resolve } from 'pathe'
+import fg from 'fast-glob'
+import { execa } from 'execa'
+import { describe, expect, it } from 'vitest'
+
+describe('should fails', async () => {
+ const root = resolve(__dirname, '../failing')
+ const files = await fg('*.test-d.*', { cwd: root })
+
+ it('typecheck files', async () => {
+ // in Windows child_process is very unstable, we skip testing it
+ if (process.platform === 'win32' && process.env.CI)
+ return
+
+ const { stderr } = await execa('npx', [
+ 'vitest',
+ 'typecheck',
+ '--dir',
+ 'failing',
+ '--config',
+ resolve(__dirname, './vitest.config.ts'),
+ ], {
+ cwd: root,
+ reject: false,
+ env: {
+ ...process.env,
+ CI: 'true',
+ NO_COLOR: 'true',
+ },
+ })
+
+ expect(stderr).toBeTruthy()
+ const lines = String(stderr).split(/\n/g)
+ const msg = lines
+ .filter(i => i.includes('TypeCheckError: '))
+ .reverse()
+ .join('\n')
+ .trim()
+ .replace(root, '')
+ expect(msg).toMatchSnapshot()
+
+ files.forEach((file) => {
+ const index = lines.findIndex(val => val.includes(`${file}:`))
+ const msg = lines.slice(index, index + 8).join('\n')
+ expect(msg).toMatchSnapshot(file)
+ })
+ }, 30_000)
+})
diff --git a/test/typescript/test/vitest.config.ts b/test/typescript/test/vitest.config.ts
new file mode 100644
index 000000000000..9c971afea0b4
--- /dev/null
+++ b/test/typescript/test/vitest.config.ts
@@ -0,0 +1,10 @@
+import { defineConfig } from 'vitest/config'
+
+export default defineConfig({
+ test: {
+ typecheck: {
+ allowJs: true,
+ include: ['**/*.test-d.*'],
+ },
+ },
+})
diff --git a/tsconfig.json b/tsconfig.json
index 972ba657fdbd..22d442ff7374 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -40,6 +40,7 @@
"./packages/vitest/*.d.ts",
"./packages/ui/client/**",
"./examples/**/*.*",
- "./bench/**"
+ "./bench/**",
+ "./test/typescript/**"
]
}