jest 单元测试

jest 单元测试

API

断言语句

  • describe用于对测试用例进行逻辑分组,使得测试代码更加有组织、易读
  • expect用于验证代码的行为是否符合预期
  • test 用于定义测试用例
  • toBe相当于===,即全等
  • toEqual相当于==
  • toBeNull匹配null
  • toBeUndefined匹配undefined
  • toBeDefined匹配已定义的
  • toBeTruthy匹配真值(指的是在布尔值上下文中,转换后的值为 true 的值)
  • toBeFalsy匹配假值( false0-00n""nullundefinedNaN
  • toBeGreaterThan大于
  • toBeGreaterThanOrEqual大于等于
  • toBeLessThan小于
  • toBeLessThanOrEqual小于等于
  • toBeCloseTo用于断言两个数字是否在一定的误差范围内接近,通常用于比较浮点数
  • toMatch正则匹配
  • toContain匹配某个数组或可迭代对象是否包含特定的元素
  • toThrow匹配是否会抛出异常

钩子

  • beforeAll(() => {})在所有测试执行之前执行
  • afterAll(() => {})在所有测试执行之后执行
  • ahterEach(() => {})每个测试用例执行完后,会执行该回调

运行测试代码

// index.test.js
describe('group', () => {
    test('sum function', () => {
        expect(sum(1, 2)).toBe(3)
    })
})

有三种方式执行该用例

  • jest group index.jest.js
  • jest group.sum function index.test.js
  • jest sum function index.test.js

Mock

import {sum, map, oneUpperCaseRule} from 'zml-util/simple'
import {validPassword} from 'zml-util'

// 需要写在外层
jest.mock('zml-util/simple', () => ({
    // 1、用真实模块
    ...jest.requireActual('zml-util/simple'),
    // 2、用自己 mock 的值,相当于截断 zml-util/simple 中的函数
    oneUpperCaseRule: jest.fn(() => ({ pass: true, reason: 'one' })),
    oneNumberCaseRule: jest.fn(() => ({ pass: true, reason: 'two' }))
}))
describe('mock', () => {
    test('测试 validPassword 函数', () => {
        const res = validPassword('abc', [oneUpperCaseRule])
        expect(res.length).toBe(0)
    })
})

配置文件

// jest.config.js
module.exports = {
    moduleNameMapper: {
        '^zml-util/(.*)$': '<rootDir>/src/$1', // 配置别名,webpack 等打包工具中配置的别名,在单测文件中识别不了,所以需要在这里重新设置别名
    },
    transform: {
        '^.+\\.js?$': 'babel-jest',
    }
}

若想查看完整的配置,可执行jest --init,它会生成一个完整jest.config.js配置文件

script

// package.json
"scripts": {
  "jest": "jest", // 默认会去执行项目中 .test.js 结尾的文件(包括 test.js)
  "jest": "jest --coverage", // 生成覆盖率文件
  "jest": "jest myTestFile.test.js", // 运行单个文件
  "jest": "jest --testPathPattern=src/tests", // 只运行 src/test 目录下的测试文件
  "jest": "jest --watch", // 文件更改时自动重新运行测试
  "jest": "", //
  "jest": "", //
  "jest": "", //
  "jest": "", //
  "jest": "", //
  "jest": "", //
},

输出

QA

  • 识别不了ES6语法?

    • 安装babel

      • npm install -D @babel/core @babel/preset-env babel-jest
    • 配置babel

    • {
        "presets": ["@babel/preset-env"]
      }
      
    • 配置 Jest

    • module.exports = {
          transform: {
              '^.+\\.js?$': 'babel-jest'
          }
      }
      
  • 为什么需要 mock

    • 有时候我们希望它是独立的,不去依赖其它模块
describe('spy', () => {
    test('play fn', () => {
        const spy = jest.spyOn(video, 'play')
        video.play()
        expect(spy).toHaveBeenCalled()
    })
})
import { getName } from 'zml-util/getName'
jest.mock('zml-util/getName', () => ({
    getName: jest.fn()
}))
describe('Implementation', () =>{
    test('getName fn', () => {
        // 重新实现
        getName.mockImplementation(() => ['hello'])
        expect(getName()).toEqual(['hello'])
    })
})

相关链接:

【前端测试】第1.2章 - Jest 单元测试之模块间依赖 Fake、Stub、Mock、Spy_哔哩哔哩_bilibili

posted @   朱在春  阅读(25)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
历史上的今天:
2022-06-09 Vue 中的样式动态绑定
2022-06-09 slot 插槽
点击右上角即可分享
微信分享提示