从入门到精通:jest-when匹配器完全指南(含Jest不对称匹配器用法)
从入门到精通jest-when匹配器完全指南含Jest不对称匹配器用法【免费下载链接】jest-whenJest support for mock argument-matched return values.项目地址: https://gitcode.com/gh_mirrors/je/jest-whenjest-when是一款专为Jest打造的参数匹配工具它让开发者能够为不同参数调用的模拟函数设置特定返回值无需在mockImplementation中编写复杂的分支逻辑。本文将全面介绍如何使用jest-when提升单元测试效率包括基础用法、高级匹配技巧以及Jest不对称匹配器的结合应用。为什么选择jest-when在传统Jest测试中模拟函数的返回值通常是固定的或者需要通过复杂的条件判断来实现参数差异化返回。jest-when通过直观的链式API解决了这一痛点让测试代码更加清晰易读。核心优势保持Jest风格无需学习全新API延续Jest的使用习惯参数精准匹配支持多种匹配模式从简单值到复杂条件简化测试逻辑避免在模拟实现中编写条件分支类型安全完整的TypeScript支持提供良好的开发体验快速开始安装步骤使用npm安装npm install --save-dev jest-when或使用yarnyarn add --dev jest-when基础导入ES模块导入import { when, resetAllWhenMocks, verifyAllWhenMocksCalled } from jest-whenCommonJS导入const { when } require(jest-when)基础用法简单参数匹配最基本的用法是为特定参数设置返回值// 定义模拟函数 const fn jest.fn() // 设置参数匹配规则 when(fn).calledWith(1).mockReturnValue(one) when(fn).calledWith(2).mockReturnValue(two) // 测试调用 console.log(fn(1)) // 输出: one console.log(fn(2)) // 输出: two console.log(fn(3)) // 输出: undefined (未匹配)异步函数支持jest-when同样支持异步函数的模拟// 模拟异步函数 const fetchUser jest.fn() // 设置解析和拒绝情况 when(fetchUser).calledWith(1).mockResolvedValue({ id: 1, role: admin }) when(fetchUser).calledWith(2).mockRejectedValue(new Error(User not found)) // 使用await测试 const user await fetchUser(1) console.log(user.role) // 输出: admin高级匹配技巧多种参数类型匹配jest-when支持各种数据类型的匹配const fn jest.fn() // 数字匹配 when(fn).calledWith(1).mockReturnValue(number) // 对象匹配 when(fn).calledWith({ role: admin }).mockReturnValue(object) // 数组匹配 when(fn).calledWith([1, 2, 3]).mockReturnValue(array) // 正则表达式匹配 when(fn).calledWith(/abc/).mockReturnValue(regex) // null匹配 when(fn).calledWith(null).mockReturnValue(null)函数匹配器通过when()包装谓词函数创建自定义匹配器// 创建自定义匹配器 const divisibleBy3 when((arg: number) arg % 3 0) // 使用自定义匹配器 when(fn).calledWith(divisibleBy3).mockReturnValue(divisible by 3) console.log(fn(3)) // 输出: divisible by 3 console.log(fn(6)) // 输出: divisible by 3 console.log(fn(5)) // 输出: undefined组合匹配器使用when.allArgs()组合多个参数匹配条件// 检查所有参数是否为数字 const areNumberArgs (...args: any[]) args.every(arg typeof arg number) when(fn).calledWith(when.allArgs(areNumberArgs)).mockReturnValue(all numbers) console.log(fn(1, 2, 3)) // 输出: all numbers console.log(fn(a, 2, 3)) // 输出: undefinedJest不对称匹配器用法jest-when完美支持Jest内置的不对称匹配器让参数匹配更加灵活基本不对称匹配器when(fn).calledWith(expect.any(Number)).mockReturnValue(any number) when(fn).calledWith(expect.stringContaining(hello)).mockReturnValue(hello string) console.log(fn(123)) // 输出: any number console.log(fn(hello world)) // 输出: hello string自定义不对称匹配器结合Jest的expect.extend()创建更复杂的匹配逻辑// 扩展Jest匹配器 expect.extend({ toBeDivisibleBy(received: number, argument: number) { return { message: () expected ${received} to be divisible by ${argument}, pass: received % argument 0 } } }) // 在jest-when中使用 when(fn).calledWith(expect.toBeDivisibleBy(5)).mockReturnValue(divisible by 5) console.log(fn(10)) // 输出: divisible by 5 console.log(fn(7)) // 输出: undefined测试验证与清理验证匹配器调用使用verifyAllWhenMocksCalled()确保所有匹配器都被调用import { verifyAllWhenMocksCalled } from jest-when // 设置匹配器 when(fn).calledWith(1).mockReturnValue(one) when(fn).calledWith(2).mockReturnValue(two) // 调用其中一个 fn(1) // 验证所有匹配器都被调用将抛出错误 verifyAllWhenMocksCalled() // 失败预期调用with(2)但未调用重置匹配器有多种方式可以重置匹配器// 重置特定匹配器 when(fn).calledWith(1).mockReset() // 重置所有匹配器 when(fn).resetWhenMocks() // 重置所有mock的匹配器 resetAllWhenMocks() // 使用Jest原生方法重置 fn.mockReset()最佳实践类型安全使用jest-when提供完整的TypeScript支持确保类型安全// 类型化模拟函数 const add jest.fn((a: number, b: number) a b) // 类型检查参数 when(add).calledWith(1, 2).mockReturnValue(3) // 正确 when(add).calledWith(1, 2).mockReturnValue(3) // TypeScript错误测试覆盖率结合verifyAllWhenMocksCalled确保测试覆盖所有分支afterEach(() { verifyAllWhenMocksCalled() resetAllWhenMocks() })合理组织测试代码将相关的when匹配器分组提高可读性describe(user service, () { const getUser jest.fn() beforeEach(() { // 用户ID 1的情况 when(getUser).calledWith(1).mockResolvedValue({ id: 1, name: Ada, role: admin }) // 用户ID 2的情况 when(getUser).calledWith(2).mockResolvedValue({ id: 2, name: Bob, role: user }) }) // 测试用例... })总结jest-when通过直观的API和强大的匹配能力极大简化了Jest测试中的模拟函数参数处理。无论是简单的参数匹配还是复杂的条件判断都能通过清晰的链式调用来实现让测试代码更加可读和可维护。结合Jest的不对称匹配器更能应对各种复杂的测试场景是Jest用户提升测试效率的必备工具。要开始使用jest-when只需通过npm安装然后导入when函数即可开始编写更优雅的测试代码。【免费下载链接】jest-whenJest support for mock argument-matched return values.项目地址: https://gitcode.com/gh_mirrors/je/jest-when创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考