大致步骤
- 准备数据
- 验证
一、准备数据
数据的位置
- 内联
- 隐式
准备方式
- 内联
js
it('should be ok', () => {
// 通过后门的方式准备数据(不推荐:暴露逻辑结构,不利于后续维护)
const todo = {
id: 1,
title: 'test',
completed: false
}
addTodo(todo)
})
委托
- 通过工厂函数来准备数据
- roundtrip,调用非公开 API 准备数据
隐式 beforeEach 钩子中准备数据:逻辑分割问题,解决方式:可以使用
suite
函数来整合测试用例。
二、验证
验证方式
- 验证状态
- 验证行为
程序的间接输入
依赖函数调用
- vi.mock + vi.mocked + mockReturnValuejs
vi.mock('xxx.js', () => { return { xxxfn: () => 1 } }) it('xxx', () => { vi.mocked(xxxfn).mockReturnValueOnce(1) })
- vi.doMock
第三方库
js
vi.mock('axios')
it('第三方库axios', async () => {
vi.mocked(axios).request.mockResolvedValueOnce({
name: 'axios',
age: 18
})
vi.mocked(axios.get).request.mockResolvedValueOnce({
name: 'axios',
age: 18
})
const res = await asyncFnc()
expect(res.age).toEqual(18)
})
对象
全局导入并在测试用例中修改
Class
通过修改原型对象的方式修改
js
class Todo {
}
it('should be ok', () => {
Todo.prototype.add = function () {
}
})
常量
js
// a.js
export const name = 'xxx'
export const age = 18
// a.test.js
vi.mock('./a', async (importOriginal) => {
// 方式一:不影响原有导出的常量属性
const original = await importOriginal()
/*
方式二:
const {name } = await vi.importActual('./a')
*/
return {
...config,
name: 'xxx-test',
}
})
it('should be ok', () => {
const n = getName()
expect(n).toEqual('xxx-test')
})
环境变量 ENV
测试调试
- JavaScript Debug Terminal
- launch.json + F5
json
{
// 想了解更多的信息, 请访问:https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Debug Current Test File",
"autoAttachChildProcesses": true,
"skipFiles": ["<node_internals>/**", "**/node_modules/**"],
"program": "${workspaceRoot}/node_modules/vitest/vitest.mjs",
"args": ["run", "${relativeFile}"],
"smartStep": true,
"console": "integratedTerminal"
}
]
}
- Vitest 插件
- vitest --ui