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

如何使用jest.useFakeTimers().setSystemTime()?解决类型不存在报错

解决jest.useFakeTimers().setSystemTime()的使用与类型报错问题

正确使用方法

jest.useFakeTimers().setSystemTime()用于在测试中模拟系统时间,步骤如下:

  1. 在测试用例执行前启用假定时器并设置目标时间
  2. 编写依赖时间的测试逻辑
  3. 测试完成后恢复真实定时器避免影响其他用例

示例代码:

// 全局或测试块内设置假时间
jest.useFakeTimers().setSystemTime(new Date('2023-01-01T00:00:00'));

test('验证当前年份是否为2023', () => {
  expect(new Date().getFullYear()).toBe(2023);
});

// 测试后清理
afterEach(() => {
  jest.useRealTimers();
});

解决"Property 'setSystemTime' does not exist on type 'typeof jest'"报错

这个报错通常是Jest类型定义版本不兼容或配置问题导致的,以下是几种修复方案:

1. 同步Jest与@types/jest版本

setSystemTime是Jest 26.6.0版本新增的API,确保你的jest和@types/jest版本一致且不低于该版本。执行更新命令:

npm install jest@latest @types/jest@latest --save-dev
# 或使用yarn
yarn add jest@latest @types/jest@latest --dev

2. 检查TypeScript配置

确保tsconfig.json的compilerOptions.types中包含jest,让TypeScript正确识别Jest类型:

{
  "compilerOptions": {
    "types": ["jest"]
  }
}

3. 使用类型断言临时绕过(不推荐长期使用)

如果暂时无法更新依赖,可以通过类型断言强制指定类型:

(jest.useFakeTimers() as jest.FakeTimers).setSystemTime(new Date('2023-01-01'));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 22:10:26