even

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
  161 随笔 :: 0 文章 :: 5 评论 :: 10万 阅读
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

1、jest安装与初始化

yarn add jest -D
yarn add @types/jest ts-jest typescript  -D  // typescript环境目录下

npx ts-jest config:init    // 默认在根目录下会生成jest.config.js的默认配置

2、代码测试覆盖率

复制代码
npx jest  --coverage  // 进行代码覆盖率的测试

npx jest // 表示进行测试

npx jest --watch // 需要在git的环境下运行

npx jest --watchAll // 不退出进行进行不断测试 coverageDirectory: "coverage", // 在jest.config.js下的配置,表示报告的放置地方
复制代码

3、jest的常用匹配器

复制代码
test('测试', () => {
  // toBe匹配器
  //   expect(sum(1, 3)).toBe(4)

  // 匹配值相等的匹配器
  //   const a = { one: 1 }
  //   expect(a).toEqual({ one: 1 })

  //值是否为null
  //   const b = null
  //   expect(b).toBeNull()

  // 值是否是undefined
  //   expect(5).toBeUndefined()

  // 表示是否被声明
  //   const c = null
  //   expect(c).toBeDefined()

  //   expect(0).toBeTruthy() // 是否为真, 会被js转换
  //   expect(1).toBeFalsy() //是否为假

  // expect(1).not.toBeTruthy() //作用的效果与toBeFalsy相同,表示取反的意思

  //数字相关的匹配器
  // expect(10).toBeGreaterThan(9) // 表示10比9大
  // expect(10).toBeGreaterThanOrEqual(10) // 比上面多个等于的判断
  // expect(9).toBeLessThan(10) // 表示9比10小
  // expect(9).toBeLessThanOrEqual(9) // 比上面多个等于的判断
  // expect(0.1 + 0.3).toBeCloseTo(0.4) // 用于小数计算后的值的比对

  // 字符相关的匹配器
  // const str = 'http://www.baidu.com'
  // expect(str).toMatch('baidu')  // 使用字符进行匹配
  // expect(str).toMatch(/baidu/) //使用正则进行匹配

  // array set相关的匹配器
  // const arr = ['aaa', 'bbb', 'ccc']
  // expect(arr).toContain('ccc')
  // const set = new Set(['aaa', 'bbb', 'ccc'])
  // expect(set).toContain('bbb')

  //处理异常的匹配器
  const test = () => {
    throw new Error('error')
  }
  expect(test).toThrow('error') // 里面的字符表示抛出的异常,也可以写正则表达式
  // expect(test).not.toThrow() // 不可以通过
})
复制代码

 4、jest异步代码的单元测试

 通过异步回调的形式实现

复制代码
// 逻辑代码部份

// 模仿进行ajax请求,返回数据
const getData = (): Promise<Record<string, any>> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ result: false })
    }, 3000)
  })
}

// 通过回调的形式拿到数据
export const asyncData = (fn: (res: Record<string, any>) => void): void => {
  getData().then((res) => {
    fn(res)
  })
}

// 测试代码部份

import { asyncData } from './index'

// 这个时候测试的时候,需要在回调函数中加入done这个函数方法,只有在结果进行返回的时候才确认请求结束,否则测试结果不准确
test('异步测试', (done) => {
  asyncData((res) => {
    expect(res).toEqual({ result: true })
    done()
  })
})
复制代码

 通过async await 的方式进行调用

复制代码
// 逻辑代码部份
// 模仿进行ajax请求,返回数据
const getData = (): Promise<Record<string, any>> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve({ result: false })
    }, 3000)
  })
}

// 通过回调的形式拿到数据
export const asyncData = (): Promise<Record<string, any>> => {
  return getData()
}

// 测试代码部份
// 方式一
// 这个时候需要return异步结果
// test('异步测试', () => {
//   return asyncData().then((res) => {
//     expect(res).toEqual({ result: true })
//   })
// })

// 方式二
test('异步测试', async () => {
  const res = await asyncData()
  expect(res).toEqual({ result: true })
})
复制代码

 在原有逻辑代码的基础上,做分支检测判断

复制代码
test('异步测试', () => {
  expect.assertions(1)  // 表示下面的逻辑一定有一个expect会被执行,里面的参数表示会被执行的expect的个数
  return asyncData()
    .then((res) => {
      expect(res).toEqual({ result: true })
    })
    .catch((err) => {
      expect(err.message).toMatch('error')
    })
})
复制代码

 jest内部支持的异步测试

复制代码
test('异步测试', async () => {
  // return expect(asyncData()).resolves.toMatchObject({
  //   result: true,
  // })

  // await expect(asyncData()).resolves.toMatchObject({
  //   result: true,
  // })

  // return expect(asyncData()).rejects.toThrow('error')
  await expect(asyncData()).rejects.toThrow('error')
})
复制代码

 jest的钩子函数以及分组

复制代码
import { asyncData } from './index'

describe('this is outer first', () => {
  beforeAll(() => {  // 表示在所有测试用例跑之前运行
    console.log('this is beforeAll') 
  })
  beforeEach(() => { // 表示在每个测试用例跑之前运行
    console.log('this is beforeEach')
  })

  afterAll(() => { // 表示在所有的测试用例完成之后运行
    console.log('this is afterAll')
  })

  afterEach(() => { // 表示在每个测试用完成后运行
    console.log('this is afterEach')
  })

  describe('this is inner first', () => {
    beforeAll(() => { // 表示在当前的分组内的所有测试用例运行之前运行
      console.log('this is inner beforeAll')
    })
    beforeEach(() => { // 表示在当前分组内的每个测试用例运行之前运行
      console.log('this is inner beforeEach')
    })
    it('this is test', () => {
      return expect(asyncData()).rejects.toThrow('error')
    })
  })
})
复制代码

注意: describe是一个分组的概念,表示对指定块的测试进行分组,组外与组内的钩子的运行顺序是先组外后组内

 

 

 

 

 

 

 

 

 

 

 

 

posted on   even_blogs  阅读(169)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2021-02-25 node学习笔记(三)--- 网络协议
点击右上角即可分享
微信分享提示