You need to enable JavaScript to run this app. 使用Jest测试基于Luxon DateTime的年龄计算函数时diffNow报错如何解决
优惠活动
大模型
产品
解决方案
定价
更多

使用Jest测试基于Luxon DateTime的年龄计算函数时diffNow报错如何解决

错误原因
  • 参数类型不匹配:calculateAge定义的入参要求是Luxon的DateTime实例,你直接传入了字符串'1950-02-02',字符串本身没有diffNow方法,因此触发类型错误。
  • jest.spyOn用法错误:spyOnAPI要求第一个参数为挂载目标方法的对象,第二个参数为目标方法名的字符串形式,你当前的传参完全不符合API规范。同时你当前的测试逻辑设计不合理:如果只是验证calculateAge的计算结果,不需要用spy监听调用,直接测试返回值即可。
正确测试代码示例

首先测试calculateAge的计算逻辑正确性:

import { DateTime } from 'luxon'
import { calculateAge } from './你的工具文件路径'

// 测试年龄大于1岁时的年数计算
it('calculates age in years correctly for birth date over 1 year ago', () => {
  // 先将日期字符串转为Luxon DateTime实例
  const testBirthDate = DateTime.fromISO('1950-02-02')
  // Mock系统时间,避免测试结果随当前时间变化
  jest.useFakeTimers().setSystemTime(new Date('2024-02-03'))

  const age = calculateAge(testBirthDate)
  expect(age).toBe('74')

  // 测试完成后恢复真实时间
  jest.useRealTimers()
})

// 测试年龄小于1岁时的月数计算
it('calculates age in months correctly for birth date less than 1 year ago', () => {
  const testBirthDate = DateTime.fromISO('2023-06-02')
  jest.useFakeTimers().setSystemTime(new Date('2024-02-03'))

  const age = calculateAge(testBirthDate)
  expect(age).toBe('8')

  jest.useRealTimers()
})

如果你确实需要监听calculateAge是否被外部调用(比如测试组件内逻辑),jest.spyOn的正确用法如下:

it('calls calculateAge when component renders', () => {
  // 第一个参数为导出calculateAge的模块对象,第二个参数为方法名字符串
  const calculateAgeSpy = jest.spyOn(require('./你的工具文件路径'), 'calculateAge')
  // 这里写触发调用的逻辑,比如渲染对应组件
  // render(<UserInfo birthDate="1950-02-02" />)

  expect(calculateAgeSpy).toHaveBeenCalled()
  // 清理spy
  calculateAgeSpy.mockRestore()
})
注意事项
  • 所有传入calculateAge的参数必须先通过DateTime.fromISO()、DateTime.fromJSDate()等API转换为Luxon的DateTime实例,不能直接传入字符串或原生Date对象。
  • 涉及时间计算的测试必须Mock系统时间,保证测试结果的稳定性,不会随运行时间变化而失效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 04:54:01