首页 > 解决方案 > 在 typescript 节点项目中使用 monorepo 样式测试目录时,ts-jest 找不到类型信息

问题描述

我使用referencesandcomposite设置分离了 jest 的测试类型和项目的类型。但是 ts-jest 无法在测试文件中找到类型信息并引发多个错误,例如:error TS2304: Cannot find name 'expect'.

这是目录结构:

.
├── package.json
├── src
│   └── index.ts
├── tests
│   ├── index.test.ts
│   └── tsconfig.json
├── tsconfig.json

tsconfig.json

{
  "compilerOptions": {
    "composite": true,
  },
  "include": ["src"]
}

tests/tsconfig.json

{
  "extends": "../tsconfig.json",
  "references": [
    {
      "name": "my-lib",
      "path": ".."
    }
  ],
  "compilerOptions": {
    "types": ["jest"],
    "rootDir": "..",
    "noEmit": true
  },
  "include": ["."]
}

package.json

{
  "jest": {
    "preset": "ts-jest",
    "environment": "node"
  }
}

如何将 ts-jest 集成到这样的项目中?

标签: node.jstypescripttestingjestjsts-jest

解决方案


更新 jest 配置以准确定义 tsconfig 文件ts-jest

package.json

{
  "jest": {
    "preset": "ts-jest",
    "environment": "node",
    "globals": {
      "ts-jest": {
        "tsconfig": "./tests/tsconfig.json"
      }
    }
  }
}

推荐阅读