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

NX工作区Angular项目Jest单元测试导入Clarity组件报错

问题描述

在NX工作区的Angular项目中使用Jest编写单元测试时,导入Clarity组件会导致测试失败。

复现步骤

  • 创建NX工作区:npx create-nx-workspace@latest
  • 安装Clarity依赖:npm i @cds/{core,angular} --legacy-peer-deps
  • 在测试代码中导入CdsButtonModule并加入测试模块后,Jest抛出错误:SyntaxError: Cannot use import statement outside a module

解决方案

该问题源于Clarity的@cds/core包采用ES模块语法,但Jest默认未正确处理这类模块,可通过以下步骤修复:

  1. 调整Jest配置,让其转译@cds相关包
    在项目根目录的jest.config.ts(或jest.config.js)中,更新transformIgnorePatterns配置,排除@cds包的忽略转译规则:

    export default {
      // 其他现有配置
      transformIgnorePatterns: [
        'node_modules/(?!@cds/core|@cds/angular)'
      ]
    };
    
  2. 确认Angular Jest预设配置正确
    确保jest配置中使用NX官方的Angular预设:

    export default {
      preset: '@nrwl/angular/jest',
      // 其他现有配置
    };
    
  3. 清理缓存并重新执行测试
    先清除Jest缓存避免旧配置干扰:

    npx jest --clearCache
    

    再运行项目测试:

    nx test your-project-name
    

备选方案(若上述步骤无效)

  • 升级@nrwl/jest和@angular-builders/jest至最新兼容版本
  • 在tsconfig.spec.json中,将@cds/core和@cds/angular添加到types数组中
  • 检查package.json是否设置了"type": "module",若有需调整Jest配置适配ES模块

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 16:45:38