You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Jest测试countBy函数的两个入参是否为整数类型

问题分析

你原有测试未达预期有两个核心原因:

  • countBy 函数的返回值是数组,typeof 数组 的执行结果是 object,永远不可能等于 'number',断言逻辑本身不成立
  • 原有写法仅判断了返回值的顶层类型,完全没覆盖「入参必须为整数」的校验逻辑
正确实现方案

我们分两个测试场景覆盖需求,默认你使用的是 Jest 类单测框架:

1. 入参合法性测试

先给 countBy 函数加上入参校验逻辑(非法入参时抛出错误),再编写对应测试:

it('should only accept integer type parameters', () => {
  // 验证value为非整数时的拦截表现
  expect(() => countBy('1', 5)).toThrow() // 字符串类型
  expect(() => countBy(1.5, 5)).toThrow() // 浮点数
  expect(() => countBy(null, 5)).toThrow() // 空值
  expect(() => countBy(undefined, 5)).toThrow()
  
  // 验证number为非整数时的拦截表现
  expect(() => countBy(2, '5')).toThrow()
  expect(() => countBy(2, 3.2)).toThrow()
  expect(() => countBy(2, null)).toThrow()
  
  // 验证合法入参可以正常执行
  expect(() => countBy(2,5)).not.toThrow()
})

2. 返回值合法性测试

验证返回结果格式、元素类型符合要求:

it('should return an array composed of integers', () => {
  const result = countBy(2,5)
  // 验证返回值是数组
  expect(Array.isArray(result)).toBe(true)
  // 验证数组长度符合入参要求
  expect(result.length).toBe(5)
  // 验证数组所有元素都是整数
  expect(result.every(Number.isInteger)).toBe(true)
  // 也可以用Jest内置匹配器简化写法
  expect(result).toEqual(expect.arrayContaining([expect.any(Number)]))
})
补充说明

你贴的示例存在两个笔误:countBy(1, 10) 返回值里多写了一个5(第六位应为6),第二个示例函数名误写为 countyBy,实际编码时注意规避。

内容的提问来源于stack exchange,提问作者Kelson Batista

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 02:06:01