Jest单元测试效率提升50%jest-when核心功能全解析【免费下载链接】jest-whenJest support for mock argument-matched return values.项目地址: https://gitcode.com/gh_mirrors/je/jest-whenjest-when是一款专为Jest设计的参数匹配返回值工具它让开发者能够为不同的函数调用参数设置特定的返回值无需在mockImplementation中编写复杂的分支逻辑从而显著提升单元测试的编写效率和可读性。为什么选择jest-when在普通的Jest测试中我们通常这样创建mock函数const fn jest.fn() fn.mockReturnValue(yay!)这种方式的问题在于无论函数如何调用都只会返回固定的值。当需要根据不同参数返回不同结果时我们不得不编写冗长的条件判断fn.mockImplementation((arg) { if (arg 1) return one if (arg 2) return two return undefined })而使用jest-when代码会变得异常简洁import { when } from jest-when const fn jest.fn() when(fn).calledWith(1).mockReturnValue(one) when(fn).calledWith(2).mockReturnValue(two)快速安装与配置 ⚡一键安装步骤通过npm安装jest-whennpm install --save-dev jest-when兼容性说明支持Jest 27及以上版本适用于JavaScript和TypeScript项目推荐使用命名导入方式import { when, resetAllWhenMocks, verifyAllWhenMocksCalled } from jest-whenCommonJS环境下也支持require导入const { when } require(jest-when)核心功能详解 基础参数匹配jest-when的核心功能是通过calledWith方法设置参数匹配规则const getUser jest.fn() // 基本参数匹配 when(getUser).calledWith(1).mockReturnValue({ id: 1, name: John }) when(getUser).calledWith(2).mockReturnValue({ id: 2, name: Jane }) expect(getUser(1)).toEqual({ id: 1, name: John }) expect(getUser(2)).toEqual({ id: 2, name: Jane }) expect(getUser(3)).toBeUndefined()重要提示calledWith使用精确的参数数量匹配。when(fn).calledWith(1)只会匹配fn(1)而不会匹配fn()、fn(1, 2)或fn(1, undefined)。异步函数处理jest-when完美支持异步函数的模拟const fetchData jest.fn() // 模拟成功返回 when(fetchData).calledWith(success).mockResolvedValue({ data: ok }) // 模拟错误返回 when(fetchData).calledWith(error).mockRejectedValue(new Error(Failed)) await expect(fetchData(success)).resolves.toEqual({ data: ok }) await expect(fetchData(error)).rejects.toThrow(Failed)高级匹配器除了基本的字面量匹配jest-when还支持多种高级匹配方式Jest非对称匹配器when(fn) .calledWith( expect.anything(), // 任何值 expect.any(Number), // 任何数字 expect.objectContaining({ // 包含特定属性的对象 enabled: true }) ) .mockReturnValue(matched)函数匹配器创建自定义函数作为匹配器// 检查对象所有属性值是否为true const allValuesTrue when((arg: Recordstring, boolean) Object.values(arg).every(Boolean) ) // 检查数字是否能被3整除 const divisibleBy3 when((arg: number) arg % 3 0) when(fn) .calledWith(allValuesTrue, divisibleBy3) .mockReturnValue(yay!) expect(fn({ a: true, b: true }, 9)).toBe(yay!) expect(fn({ a: true, b: false }, 9)).toBeUndefined()全参数匹配器使用when.allArgs对完整参数列表进行匹配// 检查所有参数是否都是数字 const areAllNumbers when.allArgs((args) args.every(arg typeof arg number) ) when(fn).calledWith(areAllNumbers).mockReturnValue(all numbers) expect(fn(1, 2, 3)).toBe(all numbers) expect(fn(1, two, 3)).toBeUndefined()链式调用与优先级jest-when支持链式调用后续定义的匹配规则会覆盖先前的同名规则when(fn) .calledWith(1).mockReturnValue(first) .calledWith(2).mockReturnValue(second) // 覆盖已有的匹配规则 when(fn).calledWith(1).mockReturnValue(updated) expect(fn(1)).toBe(updated) // 新规则生效 expect(fn(2)).toBe(second) // 未被覆盖的规则保持不变一次性返回值使用*Once系列方法设置一次性返回值when(fn) .calledWith(once) .mockReturnValueOnce(first call) .mockReturnValue(subsequent calls) expect(fn(once)).toBe(first call) // 第一次调用返回特定值 expect(fn(once)).toBe(subsequent calls) // 后续调用返回默认值 expect(fn(once)).toBe(subsequent calls) // 仍然返回默认值默认返回值设置默认返回值作为未匹配情况的回退when(fn) .calledWith(special).mockReturnValue(special value) .defaultReturnValue(default value) // 默认返回值 expect(fn(special)).toBe(special value) // 匹配特定规则 expect(fn(other)).toBe(default value) // 未匹配时返回默认值实用API参考 主要方法方法用途when(fn)包装Jest mock或spy函数calledWith(...matchers)设置参数匹配规则expectCalledWith(...matchers)设置参数匹配并断言必须被调用mockReturnValue(value)设置返回值mockResolvedValue(value)设置异步成功返回值mockRejectedValue(error)设置异步错误返回值defaultReturnValue(value)设置默认返回值resetAllWhenMocks()重置所有jest-when mockverifyAllWhenMocksCalled()验证所有mock都被调用过重置与验证jest-when提供多种重置mock的方式// 重置特定匹配规则 when(fn).calledWith(1).mockReset() // 重置某个mock的所有规则 when(fn).resetWhenMocks() // 重置所有mock resetAllWhenMocks() // 验证所有mock都被调用过 verifyAllWhenMocksCalled()实用技巧与最佳实践 严格模式下的错误处理为未匹配的调用设置抛出错误快速发现测试中的意外调用when(fn) .calledWith(expected).mockReturnValue(ok) .defaultImplementation((...args) { throw new Error(Unexpected args: ${JSON.stringify(args)}) })回调函数模拟轻松模拟需要回调的函数const callback jest.fn() when(fn) .calledWith(callback) .mockImplementation((cb) cb(called)) fn(callback) expect(callback).toHaveBeenCalledWith(called)TypeScript类型支持jest-when完全支持TypeScript提供良好的类型推断// TypeScript自动推断参数和返回值类型 const add jest.fn((a: number, b: number) a b) when(add).calledWith(2, 3).mockReturnValue(10) expect(add(2, 3)).toBe(10) // 类型安全项目结构与源码jest-when的核心实现位于以下文件主逻辑src/when.ts测试文件src/when.test.ts类型测试src/when.type-test.ts总结jest-when通过提供简洁直观的API让Jest mock函数的参数匹配和返回值设置变得异常简单。它不仅减少了测试代码量还提高了测试的可读性和可维护性是Jest用户提升单元测试效率的必备工具。无论是简单的参数匹配还是复杂的异步函数模拟jest-when都能轻松应对帮助开发者编写更清晰、更健壮的单元测试。【免费下载链接】jest-whenJest support for mock argument-matched return values.项目地址: https://gitcode.com/gh_mirrors/je/jest-when创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考