先解释一下后续要用到的类型签名
之后的类型签名中使用了以下类型
type Awaitable<T> = T | PromiseLike<T>
type TestFunction = ()=>Awaitablt<void>
//当测试函数返回承诺的时候,运行程序将会等待他被解析以收集异步期望,如果承诺被拒绝,测试就会失败
interface TestOptions {
timeout?:number//如果执行时间过长,超过timeout定义的时间,测试会失败
retry?: number//如果测试失败,会重试特定次数的测试,默认0
repeats?:number
//会重复相同的测试几次(repeats次),即使每次都会失败
//如果你有retry选项,他将会使用每一个重试在每一个周期
//对于调试随机失败有用
}
test
-
type
-
(name:string | Function,fn:Testfunction,timeout?:number | TestOptions)=>void
您也可以提供超时(以毫秒为单位)来指定终止前等待的时间,默认为5秒.可以使用testTimeout全局配置
-
别名
-
it
-
用途
-
test定义了一组相关的期望,他接受测试的名称和保存测试期望的函数
-
代码示例
//Test.test.js
import {expect,test} from "vitest"
test("should work as expect",()=>{
expect(Math.sqrt(4)).toBe(2)
})
- 测试结果
test.extend
-
type
-
(fixtures:Fixtures):TestAPI
-
补充
-
Record的用法
-
- &的用法
```JavaScript
interface AA {
name: string
}
interface BB {
name: string,
age: number
}
type A = AA & BB;
let a: A = { name: "", age: 11 }
let b: A = { name: "" }//不能将类型“{ name: string; }”分配给类型“A”。类型 "{ name: string; }" 中缺少属性 "age",但类型 "BB" 中需要该属性。
-
别名
-
it.extend
-
版本:vitest 0.32.3
-
功能
-
使用test.extend通过自定义装置扩展测试上下文,将返回一个新的test并且他也是可扩展的
-
可以根据需要扩展它来组合更多的灯具或者覆盖现有的灯具
更多可参见扩展测试上下文
-
代码
import { expect, test } from "vitest"
const todos = [];
const archive = [];
const myTest = test.extend({
todos: async ({ task }, use) => {
todos.push(1, 2, 3);
await use(todos)
todos.length = 0;
},
archive
})
myTest('add item', ({ todos }) => {
expect(todos.length).toBe(3)
todos.push(4)
expect(todos.length).toBe(4)
})
-
测试结果
test.skip
- type
- (name:string | Function,fn:TestFunciton,timeout?:number | TestOptions)=>void
- 别名
- it.skip
- 功能
- 如果你想跳过某些测试,但由于任何原因不想删除代码,则可以使用test.skip来避免运行他们
- 代码1
//skip.test.js
import { assert, test } from "vitest"
test.skip("skipped test", () => {
//Test skipped,no error
assert.equal(Math.sqrt(4), 3)
})
- 代码2
- 通过在其上下文动态调用skip来跳过测试
import { assert, test } from "vitest"
// test.skip("skipped test", () => {
// //Test skipped,no error
// assert.equal(Math.sqrt(4), 3)
// })
test('skipped test', (context) => {
context.skip()
assert.equal(Math.sqrt(4), 3)
})
-
测试结果1
-
测试结果2
test.skipif
- type
- (condition:any)=>Test
- 别名
- it.skipIf
- 功能
- 在某些情况下,您可能会在不同的环境中多次运行测试,并且某些测试可能是特定于环境的
- 您可以使用test,skipIf在条件为真的时候跳过测试,而不用if包装测试代码
- 注意
- 当使用vitest作为类型检查器的时候,不能使用此语法
- 代码
import { assert, test } from 'vitest'
const isDev = process.env.NODE_ENV === 'development'
test.skipIf(!isDev)('prod only test', () => {
// this test only runs in production
})
-
测试结果
test.runIf
- type
- (condition:any)=>Test
- 别名
- it.runIf
- 功能
- test.skipIf相反
- 注意
- 当使用vitest作为类型检查器的时候,不能使用此语法
- 代码
import { assert, test } from 'vitest'
const isDev = process.env.NODE_ENV === 'development'
test.runIf(isDev)('dev only test', () => {
// this test only runs in development
})
-
测试结果
test.only
-
type
-
(name:string | Function,fn:TestFunction,timeout?:number)=>void
您也可以提供超时(以毫秒为单位)来指定终止前等待的时间,默认为5秒.可以使用testTimeout全局配置
-
别名
-
it.only
-
功能
使用test.only仅运行给定套件中的某些测试,这在调试的时候很有用
说人话:
就初步体验而言:观察到同一个文件中出现了test.only,同一个文件的其他test会被跳过,但是其他测试文件不会被影响跳过
有时候在某个文件中运行Only测试非常有用,忽略整个测试套件中的所有其他测试(whole会污染测试输出),可以使用包含相关测试的特定文件运行vitest 即 vitest interesting.test.js
-
代码
import { assert, test } from 'vitest'
test.only('test', () => {
//只运行这个测试和其他标记为Only的测试
assert.equal(Math.sqrt(4), 2)
})
test(" as expect", () => {
expect(Math.sqrt(4)).toBe(2)
})
- 测试结果1
- 测试结果2
test.concurrent
- type
- (name:string | Function,fn:TestFunction,timeout?:number)=>void
- 别名
- it.concurrent
- 注意
- 当使用 Vitest 作为类型检查器时,不能使用此语法。
- 功能
- 标记要并行运行的连续测试,接收测试名称,包含要收集到的测试的异步函数,以及可选的超时(以毫秒为单位)
- 代码1
import { describe, test } from "vitest"
describe("suite", () => {
test("serial test", async () => { /** * **/ })
//标记为并发的两个测试将并行运行
test.concurrent("concurrent test1", async () => {/** ** **/ })
test.concurrent("concurrent test2", async () => {/** ** **/ })
})
-
测试结果1
-
代码2
test.skip,test.only,test.todo适用于并发测试一下组合均有效
import { describe, test } from "vitest"
describe("suite", () => {
test("serial test", async () => { /** * **/ })
//标记为并发的两个测试将并行运行
test.concurrent("concurrent test1", async () => {/** ** **/ })
// test.only.concurrent("concurrent test2", async () => {/** ** **/ })
test.skip.concurrent("concurrent test3", async () => {/** ** **/ })
test.todo.concurrent("concurrent test4", async () => {/** ** **/ })
})
-
测试结果2
-
代码3
-
运行并发测试的时候,快照和断言必须使用本地测试上下文的expect以确保检测到正确的测试
import { describe, test } from "vitest"
describe("suite", () => {
test.concurrent("concurrent test1", async ({ expect }) => {
expect(1).toMatchSnapshot()
})
// test.concurrent("concurrent test2", async ({ expect }) => {
// expect(2).toMatchFileSnapshot()
// })
})
-
测试结果
test.sequential
- type
- (name:string | Function,fn:TestFunction,timeout?:number)=>void
- 功能
- 将测试标记为连续的,如果您想在describe.concurrent内或者使用--sequence.concurrent命令选项按顺序运行测试,这非常有用
- 代码
import { describe, test } from "vitest"
test("concurrent test 1", async () => { })
test("concurrent test 2", async () => { })
test.sequential("sequential test 1", async () => { })
test.sequential("sequential test 2", async () => { })
describe("suite", () => {
test("concurrent test 1", async () => { })
test("concurrent test 2", async () => { })
test.sequential("sequential test 1", async () => { })
test.sequential("sequential test 2", async () => { })
})
- 测试结果
test.todo
- type
- (name:string | Function)=>void
- 别名
- it.todos
- 功能
- 使用test.todo对稍后要实现的测试进行存根,
- 测试报告中将显示一个条目,以便您了解仍然需要实施多少测试
- 代码
import { expect, test } from "vitest"
test("should work as expect", () => {
expect(Math.sqrt(4)).toBe(2)
})
test.todo("unimplemented test")
- 测试结果
test.fails
- type
- (name:string | Function,fn:TestFunction,timeout?:number)=>void
- 别名
- it.fails
- 功能
- 指示断言将显式失败
- 代码
import { expect, test } from "vitest"
function myAsync() {
return new Promise(resolve => resolve(1))
}
test.fails("fail test", async () => {
await expect(myAsync()).rejects.toBe(1)
})
-
测试结果
test.each
- type
- (cases:readonlyArray,…args:any[])=>void
- 别名
- it.each
- 功能
- 当您需要使用不同的变量运行相同的测试的时候,请使用test.each,
- 您可以按照测试函数参数的顺序在测试名称中注入printf格式的参数
- printf格式
- %s:string
- %d:number
- %i:integer
- %f:floating point value
- %j:json
- %o:object
- %#:index of the test case//测试用例的索引
- %%:单个百分号
- 注意
- 当使用 Vitest 作为类型检查器时,不能使用此语法。
- 如果您想访问
TestContext,请使用describe.each进行单个测试。 - 代码1
import { expect, test } from "vitest"
test.each([[1, 1, 2], [1, 2, 3], [2, 1, 3]])('add(%i,%i) -> %i', (a, b, expected) => {
expect(a + b).toBe(expected)
})
- 测试结果1
-
代码2
-
如果你想使用对象作为参数,您还可以使用$前缀访问对象属性
import { expect, test } from "vitest"
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)
})
-
测试结果2
-
代码3
-
如果您使用对象作为参数,您还可以使用
.访问对象属性
import { expect, test } from "vitest"
//从Vitest 0.25.3开始,您还可以使用模板字符串表。
//第一行应该是列名称,用 | 分隔;
//使用 ${value} 语法作为模板文字表达式提供的一行或多行后续数据。
//Vitest 使用 Chai format 方法处理 $values 。如果该值被截断太多,您可以在配置文件中增加 chaiConfig.truncateThreshold 。
// test.each`
// a | b | expected
// ${{ val: 1 }} | ${'b'} | ${'1b'}
// ${{ val: 2 }} | ${'b'} | ${'2b'}
// ${{ val: 3 }} | ${'b'} | ${'3b'}
// `('add($a.val, $b) -> $expected', ({ a, b, expected }) => {
// expect(a.val + b).toBe(expected)
// })
test.each([
{ a: { val: 1 }, b: "b", expected: "1b" },
{ a: { val: 2 }, b: "b", expected: "2b" },
{ a: { val: 3 }, b: "b", expected: "3b" },
])('add($a.val, $b) -> $expected', ({ a, b, expected }) => {
expect(a.val + b).toBe(expected)
})
- 测试结果3
bench
- type
- (name:string | Function,fn:BenchFunction,options?:BenchOptions)=>void
- 功能
- 定义基准,基准就是一个定义一系列的操作的函数,vitest多次运行该函数以显示不同的性能结果
- vitest在底层使用tinybench库,继承其所有可用作第三个参数的选项
- options接口
export interface Options {
time?:number//default 500 运行基准测试任务所需的时间(毫秒)
iterations?:number//default 10即使完成了time选项,任务也应该运行的次数
now?:()=>number//函数以毫秒为单位获取当前时间戳
signal?:AbortSignal//中止基准测试的abortsingal
warmupTime?:number//default:100ms 预热时间(毫秒)
warmupIteractions?:number//default 5 ,热身的迭代
setup?:Hook//每个基准测试任务周期之前运行的setup函数
teardown?:每个基准测试任务周期后运行的Teardown函数
}
- Packages.json配置
"scripts": {
"dev": "vite",
"build": "vue-tsc && vite build",
"preview": "vite preview",
"test": "vitest",
"bench":"vitest bench"
},
- 代码
import { bench } from 'vitest'
bench('normal sorting', () => {
const x = [1, 5, 4, 2, 3]
x.sort((a, b) => {
return a - b
})
}, { time: 1000 })
-
运行该文件 npm run bench src/scripts/Bench.bench.js
-
测试结果
bench.skip
- type
- (name:string | Function,fn:BenchFunction,options?:BenchOptions)=>void
- 功能
- 您可以使用bench.skip语法来跳过某些基准测试
- 代码
import { bench } from "vitest"
bench.skip("normal sorting", () => {
const x = [1, 5, 4, 2, 3]
x.sort((a, b) => {
return a - b
})
})
-
测试结果
bench.only
- type
- (name:string | Function,fn:BenchFunction,options?:BenchOptions)=>void
- 功能
- 仅仅运行给定套件中的某些基准测试,在调试的时候很有用
- 代码
import { bench } from "vitest"
bench("normal sorting1", () => {
const x = [1, 5, 4, 2, 3]
x.sort((a, b) => {
return a - b
})
})
bench.only("normal sorting2", () => {
const x = [1, 5, 4, 2, 3]
x.sort((a, b) => {
return a - b
})
})
-
测试结果
bench.todo
- type
- (name:string | Function)=>void
- 功能
- 使用bench.todo存根稍后要实现的基准
- 代码
import {bench} from "vitest"
bench.todo("unimplemented test")
- 测试结果
describe
- 前言
- 当您在文件的顶层使用test或者bench的时候,他们将作为隐士套件的一部分被收集
- 使用describe可以让您在当前上下文中定义一个新套件,作为一组相关的测试或者基准测试以及其他嵌套套件
- 套件可以让您组织测试和基准测试,使得报告更加清晰
- 代码1
import { describe, expect, test } from "vitest";
const person = {
isActive: true,
age: 32
}
describe('person', () => {
test("person is defined", () => {
expect(person).toBeDefined()
})
test("person is active", () => {
expect(person.isActive).toBeTruthy()
})
test("age limit", () => {
expect(person.age).toBeLessThanOrEqual(32)
})
})
-
测试结果1
- 代码2
import { bench, describe } from "vitest"
describe("sort", () => {
bench("normal", () => {
const x = [1, 2, 3]
x.sort((a, b) => {
return a - b
})
})
bench("reserve", () => {
const x = [1, 2, 3]
x.reverse().sort((a, b) => {
return a - b
})
})
})
-
测试结果2
-
代码3
-
如果您有测试或基准的层次结构,您还可以嵌套描述块:
import { describe, expect, test } from 'vitest'
function numberToCurrency(value) {
if (typeof value !== 'number')
throw new Error('Value must be a number')
return value.toFixed(2).toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
describe('numberToCurrency', () => {
describe('given an invalid number', () => {
test('composed of non-numbers to throw error', () => {
expect(() => numberToCurrency('abc')).toThrowError()
})
})
describe('given a valid number', () => {
test('returns the correct currency format', () => {
expect(numberToCurrency(10000)).toBe('10,000.00')
})
})
})
-
测试结果3
describe.skip
- type:
- (name: string | Function, fn: TestFunction, options?: number | TestOptions) => void
- 功能
- 在套件中使用
describe.skip以避免运行特定的描述块。 - 代码
import { assert, describe, test } from 'vitest'
describe.skip('skipped suite', () => {
test('sqrt', () => {
// Suite skipped, no error
assert.equal(Math.sqrt(4), 3)
})
test("should work as expect", () => {
expect(Math.sqrt(4)).toBe(2)
})
})
-
测试`结果
describe.skipIf
- Type:
- (condition: any) => void
- 功能
- 在某些情况下,您可能会在不同的环境中多次运行套件,并且某些套件可能是特定于环境的。您可以使用
describe.skipIf在条件为真时跳过该套件,而不是使用if包装该套件 - 注意
- 使用 Vitest 作为类型检查器时不能使用此语法。
- 代码
import { describe, test } from 'vitest'
const isDev = process.env.NODE_ENV === 'development'
describe.skipIf(isDev)('prod only test suite', () => {
// this test suite only runs in production
})
-
测试结果
describe.runIf
- Type:
- (condition: any) => void
- 功能
- 与describe.skipIf 相反。
- 注意
- 当使用 Vitest 作为类型检查器时,不能使用此语法。
- 代码
import { assert, test } from 'vitest'
const isDev = process.env.NODE_ENV === 'development'
describe.runIf(isDev)('dev only test suite', () => {
// this test suite only runs in development
})
-
测试结果
describe.only
Type:
- (name: string | Function, fn: TestFunction, options?: number | TestOptions) => void
- 功能
- 使用
describe.only仅运行某些套件 - 注意
- 当使用 Vitest 作为类型检查器时,不能使用此语法。
- 代码
// Only this suite (and others marked with only) are run
import { assert, test, describe } from 'vitest'
describe.only('suite', () => {
test('sqrt', () => {
assert.equal(Math.sqrt(4), 2)
})
})
describe('other suite', () => {
// ... will be skipped
})
- 测试环境
describe.concurrent
- Type:
- (name: string | Function, fn: TestFunction, options?: number | TestOptions) => void
- 功能
- 套件中的
describe.concurrent将每个测试标记为并发 - 注意
- 当使用 Vitest 作为类型检查器时,不能使用此语法。
- 代码
import { test, describe } from "vitest"
// 此套件中的所有测试都将并行运行
describe.concurrent('suite', () => {
test('concurrent test 1', async () => { /* ... */ })
test('concurrent test 2', async () => { /* ... */ })
test.concurrent('concurrent test 3', async () => { /* ... */ })
})
-
测试结果
-
代码2
-
.skip、.only和.todo适用于并发套件。以下所有组合均有效:
import { test, describe } from "vitest"
// 此套件中的所有测试都将并行运行
describe.concurrent('suite1', () => {
test('concurrent test 1', async () => { /* ... */ })
test('concurrent test 2', async () => { /* ... */ })
test.concurrent('concurrent test 3', async () => { /* ... */ })
})
describe.concurrent('suite2', () => {
test('concurrent test 1', async () => { /* ... */ })
test('concurrent test 2', async () => { /* ... */ })
test.concurrent('concurrent test 3', async () => { /* ... */ })
})
describe.skip.concurrent('suite3', () => {
test('concurrent test 1', async () => { /* ... */ })
test('concurrent test 2', async () => { /* ... */ })
test.concurrent('concurrent test 3', async () => { /* ... */ })
}) // or describe.concurrent.skip(/* ... */)
describe.only.concurrent('suite4', () => {
test('concurrent test 1', async () => { /* ... */ })
test('concurrent test 2', async () => { /* ... */ })
test.concurrent('concurrent test 3', async () => { /* ... */ })
}) // or describe.concurrent.only(/* ... */)
describe.todo.concurrent('suit5', () => {
test('concurrent test 1', async () => { /* ... */ })
test('concurrent test 2', async () => { /* ... */ })
test.concurrent('concurrent test 3', async () => { /* ... */ })
}) // or describe.concurrent.todo(/* ... */)
-
测试结果2
-
代码3
-
运行并发测试时,快照和断言必须使用本地测试上下文中的
expect以确保检测到正确的测试。
import { test, describe } from "vitest"
describe.concurrent('suite', () => {
test('concurrent test 1', async ({ expect }) => {
expect(1).toMatchSnapshot()
})
})
-
测试结果3
describe.sequential
- Type:
- (name: string | Function, fn: TestFunction, options?: number | TestOptions) => void
- 功能
- 套件中的
describe.sequential将每个测试标记为连续的。如果您想在describe.concurrent内或使用--sequence.concurrent命令选项按顺序运行测试,这非常有用。 - 代码
import { test, describe } from "vitest"
describe.concurrent('suite1', () => {
test('concurrent test 1', async () => { /* ... */ })
test('concurrent test 2', async () => { /* ... */ })
describe.sequential('', () => {
test('sequential test 1', async () => { /* ... */ })
test('sequential test 2', async () => { /* ... */ })
})
})
describe.concurrent('suite2', () => {
test('concurrent test 1', async () => { /* ... */ })
test('concurrent test 2', async () => { /* ... */ })
describe.concurrent('', () => {
test('sequential test 1', async () => { /* ... */ })
test('sequential test 2', async () => { /* ... */ })
})
})
describe.concurrent('suite3', () => {
test('concurrent test 1', async () => { /* ... */ })
test('concurrent test 2', async () => { /* ... */ })
test('concurrent test 3', async () => { /* ... */ })
test('concurrent test 4', async () => { /* ... */ })
})
-
测试结果
describe.todo
- Type:
- (name: string | Function) => void
- 功能
- 使用
describe.todo来存根稍后要实现的套件。测试报告中将显示一个条目,以便您了解仍需要实施多少测试。 - 代码
describe.todo('unimplemented suite')
-
测试结果
describe.each
- Type:
- (cases: ReadonlyArray, …args: any[]): (name: string | Function, fn: (…args: T[]) => void, options?: number | TestOptions) => void
- 功能
- 如果您有多个依赖于相同数据的测试,请使用
describe.each。 - 注意
- 当使用 Vitest 作为类型检查器时,不能使用此语法。
- 代码
import { test, describe, expect } from "vitest"
describe.each([
{ a: 1, b: 1, expected: 2 },
{ a: 1, b: 2, expected: 3 },
{ a: 2, b: 1, expected: 3 },
])('describe object add($a, $b)', ({ a, b, expected }) => {
test(`returns ${expected}`, () => {
expect(a + b).toBe(expected)
})
test(`returned value not be greater than ${expected}`, () => {
expect(a + b).not.toBeGreaterThan(expected)
})
test(`returned value not be less than ${expected}`, () => {
expect(a + b).not.toBeLessThan(expected)
})
})
-
测试结果
describe.shuffle
- Type:
- (name: string | Function, fn: TestFunction, options?: number | TestOptions) => void
- 功能
- itest 提供了一种通过 CLI 标志
--sequence.shuffle或配置选项sequence.shuffle以随机顺序运行所有测试的方法,但如果您只想让测试套件的一部分以随机顺序运行测试,你可以用这个标志来标记它。 - 注意
- 当使用 Vitest 作为类型检查器时,不能使用此语法。
.skip、.only和.todo适用于随机套件。- 代码
import { test, describe, expect } from "vitest"
const person = {
isActive: true,
age: 32
}
describe.shuffle('suite', () => {
test('random test 1', async () => { expect(person).toBeDefined() })
test('random test 2', async () => { expect(person.isActive).toBeTruthy() })
test('random test 3', async () => { expect(person.age).toBeLessThanOrEqual(32) })
})
// order depends on sequence.seed option in config (Date.now() by default)
-
测试结果
Setup and Teardown
- 功能
- 这些函数允许您挂钩测试的生命周期,以避免重复设置和拆卸代码。
- 它们适用于当前上下文:如果它们在顶层使用,则适用于文件;如果它们位于
describe块内,则适用于当前套件。 - 当您将 Vitest 作为类型检查器运行时,不会调用这些挂钩。
beforeEach
- Type:
- beforeEach(fn: () => Awaitable, timeout?: number)
- 功能
- 注册一个回调,在当前上下文中的每个测试运行之前调用。
- 如果函数返回一个 Promise,Vitest 将等待 Promise 解析后再运行测试。
- 您可以传递超时(以毫秒为单位)来定义终止前等待的时间。默认值为 5 秒。
- 代码
import { test, describe, expect, beforeEach } from "vitest"
function stopMocking() {
return new Promise((resolve) => {
setTimeout(() => {
console.log(111)
resolve("ok")
}, 3000)
})
}
beforeEach(async () => {
// Clear mocks and add some testing data after before each test run
await stopMocking()
})
const person = {
isActive: true,
age: 32
}
describe.shuffle('suite', () => {
test('random test 1', async () => { expect(person).toBeDefined() })
test('random test 2', async () => { expect(person.isActive).toBeTruthy() })
test('random test 3', async () => { expect(person.age).toBeLessThanOrEqual(32) })
})
// order depends on sequence.seed option in config (Date.now() by default)
-
测试结果
-
代码2
-
从 Vitest v0.10.0 开始,
beforeEach还接受可选的清理函数(相当于afterEach)。
import { test, describe, expect, beforeEach } from "vitest"
let timer
function stopMocking() {
return new Promise((resolve) => {
timer = setTimeout(() => {
console.log(111)
resolve("ok")
}, 3000)
})
}
function resetSomething(timer) {
clearTimeout(timer)
console.log("clean")
}
beforeEach(async () => {
// Clear mocks and add some testing data after before each test run
await stopMocking()
return async () => {
await resetSomething(timer)
}
})
const person = {
isActive: true,
age: 32
}
describe.shuffle('suite', () => {
test('random test 1', async () => { expect(person).toBeDefined() })
test('random test 2', async () => { expect(person.isActive).toBeTruthy() })
test('random test 3', async () => { expect(person.age).toBeLessThanOrEqual(32) })
})
// order depends on sequence.seed option in config (Date.now() by default)
-
测试结果
afterEach
- Type:
- afterEach(fn: () => Awaitable, timeout?: number)
- 功能
- 注册一个回调,在当前上下文中的每一项测试完成后调用。
- 如果函数返回一个 Promise,Vitest 会等到 Promise 解析后再继续。
- 您可以提供超时(以毫秒为单位)来指定终止前等待的时间。默认值为 5 秒。
- 代码
import { test, describe, expect, beforeEach, afterEach } from "vitest"
let timer
function stopMocking() {
return new Promise((resolve) => {
timer = setTimeout(() => {
console.log(111)
resolve("ok")
}, 3000)
})
}
function resetSomething(timer) {
clearTimeout(timer)
console.log("clean")
}
afterEach(async () => {
await resetSomething(timer) // clear testing data after each test run
})
beforeEach(async () => {
// Clear mocks and add some testing data after before each test run
await stopMocking()
})
const person = {
isActive: true,
age: 32
}
describe.shuffle('suite', () => {
test('random test 1', async () => { expect(person).toBeDefined() })
test('random test 2', async () => { expect(person.isActive).toBeTruthy() })
test('random test 3', async () => { expect(person.age).toBeLessThanOrEqual(32) })
})
// order depends on sequence.seed option in config (Date.now() by default)
-
测试结果
beforeAll
- Type:
- beforeAll(fn: () => Awaitable, timeout?: number)
- 功能
- 注册一个回调,在开始运行当前上下文中的所有测试之前调用一次。
- 如果函数返回一个 Promise,Vitest 将等待 Promise 解析后再运行测试。
- 您可以提供超时(以毫秒为单位)来指定终止前等待的时间。默认值为 5 秒。
- 从 Vitest v0.10.0 开始,
beforeAll还接受可选的清理函数(相当于afterAll) - 代码
import { test, describe, expect, beforeAll } from "vitest"
let timer
function stopMocking() {
return new Promise((resolve) => {
timer = setTimeout(() => {
console.log(111)
resolve("ok")
}, 3000)
})
}
function resetSomething(timer) {
clearTimeout(timer)
console.log("clean")
}
// afterEach(async () => {
// await resetSomething(timer) // clear testing data after each test run
// })
beforeAll(async () => {
// Clear mocks and add some testing data after before each test run
await stopMocking()
})
const person = {
isActive: true,
age: 32
}
describe.shuffle('suite', () => {
test('random test 1', async () => { expect(person).toBeDefined() })
test('random test 2', async () => { expect(person.isActive).toBeTruthy() })
test('random test 3', async () => { expect(person.age).toBeLessThanOrEqual(32) })
})
// order depends on sequence.seed option in config (Date.now() by default)
-
测试结果
afterAll
- Type:
- afterAll(fn: () => Awaitable, timeout?: number)
- 功能
- 注册一个回调,在当前上下文中运行所有测试后调用一次。
- 如果函数返回一个 Promise,Vitest 会等到 Promise 解析后再继续。
- 或者,您可以提供超时(以毫秒为单位)来指定终止前等待的时间。默认值为 5 秒。
- 代码
import { test, describe, expect, beforeAll, afterAll } from "vitest"
let timer
function stopMocking() {
return new Promise((resolve) => {
timer = setTimeout(() => {
console.log(111)
resolve("ok")
}, 3000)
})
}
function resetSomething(timer) {
clearTimeout(timer)
console.log("clean")
}
afterAll(async () => {
await resetSomething(timer) // clear testing data after each test run
})
beforeAll(async () => {
// Clear mocks and add some testing data after before each test run
await stopMocking()
})
const person = {
isActive: true,
age: 32
}
describe.shuffle('suite', () => {
test('random test 1', async () => { expect(person).toBeDefined() })
test('random test 2', async () => { expect(person.isActive).toBeTruthy() })
test('random test 3', async () => { expect(person.age).toBeLessThanOrEqual(32) })
})
// order depends on sequence.seed option in config (Date.now() by default)
-
测试结果