Vitest
2024-04-12 本文已影响0人
sweetBoy_9126
test/it
-
it: BDD 行为驱动开发基于 TDD(测试驱动开发)
用法:it should xxx xxx
相关框架: Mocha, Jasmine -
test
相关框架:jest
用法:test("should xxx xxxx", () => {})
风格问题
describe
创建一个测试套件
帮助我们把相同行为的测试放在一起,方便我们维护我们的测试
describe('add', () => {})
expect
- toBe 等于
全等 ===
场景:一般用于基本类型
it('toBe', () => {
expect(1).toBe(1)
})
- toEqual 等于
场景:对象之间的比较
it('toEqual', () => {
const user = { name: 'lifa' }
expect(user).toEqual({name: 'lifa'})
})
- toBeTruthy
场景:当前值是一个真值
it('toBeTruthy', () => {
expect(1).toBeTruthy()
expect(true).toBeTruthy()
expect('1234').toBeTruthy()
})
- toBeFalsy
场景:当前值是一个假值
it('toBeFalsy', () => {
expect(0).toBeFalsy()
expect(false).toBeFalsy()
expect('').toBeFalsy()
})
- toContain
包含某个值
场景:数组/string里是否包含某个值
it('toContain', () => {
const item1 = {name: 'lifa'}
const list = [item1]
expect(list).toContain(item1)
expect('<div>1234</div>').toContain('1234')
})
- toThrow
场景:检测函数会不会抛出 error
it('toThrow', () => {
function getName(name) {
if (typeof name !== 'string') {
throw new Error('错误的name')
}
return 'hei'
}
expect(() => {getName(111)}).toThrow()
expect(() => {getName(111)}).toThrow('错误的name')
})
setup & teardown
执行顺序
- beforeAll
当前文件所用的test之前调用,只执行一次
场景:数据库连接、创建临时文件
配合 return 代替 afterAll
beforeAll(() => {
return () => {
// afterAll
}
})
- beforeEach
每个 test 之前调用,每次都会执行
场景:pinia 每次创建一个新的 store
配合 return 代替 afterEach
beforeEach(() => {
return () => {
// afterEach
}
})
afterEach
每个 test 之后调用,每次都会执行
- afterAll
当前文件所用的test之后调用,只执行一次
场景:数据库断开连接、临时文件需要删除
import {beforeAll, beforeEach, afterEach, afterAll} from 'vitest'
beforeAll(() => {
console.log('before all')
})
beforeEach(() => {
console.log('before each')
})
test('frist', () => {
console.log('first')
})
test('second', () => {
console.log('second')
})
afterEach(() => {
console.log('after each')
})
afterAll(() => {
console.log('after all')
})
执行顺序为
before all -> before each -> first -> after each -> before each -> second -> after each -> after all
加入 describe
beforeAll(() => {
console.log('before all')
})
beforeEach(() => {
console.log('before each')
})
test('frist', () => {
console.log('first')
})
test('second', () => {
console.log('second')
})
afterEach(() => {
console.log('after each')
})
afterAll(() => {
console.log('after all')
})
describe('sub', () => {
beforeEach(() => {
console.log('sub: before each')
})
test('sub first', () => {
console.log('sub first')
})
afterEach(() => {
console.log('sub: after each')
})
})
before all -> before each -> first -> after each -> before each -> second -> after each -> before each -> sub:before each -> sub first -> sub: after each -> after each -> after all
会先执行外部的 beforeEach 然后再内部的
filter
- test.only
只执行这个 test - test.skip
跳过这个 test - test.todo('')
注释:列举我们要实现的,等到我们实现后就把.todo 删掉
// xxx add
test.todo('add')
- 启用命令
pnpm test 具体的文件名
pnpm test test.spec
ci
scripts: {
"test": "vitest"
}
默认是 watch 模式每次修改后都会重新执行,如果不想后面加 run,运行一次就退出
vscode 插件
vitest snippets
jest snippets