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

Jest报错TypeScript语法:const声明需初始化值的解决方法

问题:Jest执行yarn test时误报TypeScript常量未初始化

执行yarn test命令时,Jest抛出错误提示:

'Const declarations' require an initialization value.

但实际代码中已完成变量初始化:

> 4 | const config: HardhatUserConfig = {
    |             ^
  5 |   solidity: "0.8.9",
  6 |   paths: {
  7 |     artifacts: "./src/artifects",

推测是Jest未正确识别TypeScript语法,可通过以下步骤解决:

解决步骤

  • 安装TypeScript相关的Jest依赖
    执行命令:yarn add -D ts-jest @types/jest

  • 配置Jest使用TypeScript转换器
    可以通过命令生成默认配置:npx ts-jest config:init,生成的jest.config.js会自动配置ts-jest作为转换器;
    也可以手动修改jest.config.js,确保配置如下:

    module.exports = {
      preset: 'ts-jest',
      testEnvironment: 'node',
      transform: {
        '^.+\\.tsx?$': 'ts-jest',
      },
      moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
    };
    
  • 检查TypeScript编译配置
    打开tsconfig.json,确保target字段设置为ES6或更高版本(const是ES6语法,过低的目标版本会导致解析异常):

    {
      "compilerOptions": {
        "target": "ES6",
        // 其他编译配置...
      }
    }
    
  • 确认测试文件后缀
    确保你的测试文件使用.test.ts或.spec.ts后缀,Jest默认会识别这类文件。

完成以上配置后,重新执行yarn test即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 03:54:28