Vitest

2024-04-12  本文已影响0人  sweetBoy_9126

test/it

风格问题

describe

创建一个测试套件
帮助我们把相同行为的测试放在一起,方便我们维护我们的测试

describe('add', () => {})

expect

it('toBe', () => {
  expect(1).toBe(1)
})
it('toEqual', () => {
  const user = { name: 'lifa' }
  expect(user).toEqual({name: 'lifa'})
})
it('toBeTruthy', () => {
  expect(1).toBeTruthy()
  expect(true).toBeTruthy()
  expect('1234').toBeTruthy()
})
it('toBeFalsy', () => {
  expect(0).toBeFalsy()
  expect(false).toBeFalsy()
  expect('').toBeFalsy()
})
it('toContain', () => {
  const item1 = {name: 'lifa'}
  const list = [item1]
  expect(list).toContain(item1)

  expect('<div>1234</div>').toContain('1234')
})
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(() => {
  return () => {
    // afterAll
  }
})
beforeEach(() => {
  return () => {
    // afterEach
  }
})

afterEach
每个 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

  1. test.only
    只执行这个 test
  2. test.skip
    跳过这个 test
  3. test.todo('')
    注释:列举我们要实现的,等到我们实现后就把.todo 删掉
// xxx add 
test.todo('add')
  1. 启用命令
    pnpm test 具体的文件名
pnpm test test.spec

ci

scripts: {
  "test": "vitest"
}

默认是 watch 模式每次修改后都会重新执行,如果不想后面加 run,运行一次就退出

vscode 插件

vitest snippets
jest snippets

上一篇下一篇

猜你喜欢

热点阅读