Typescript jest 全局变量示例

Jun*_*ndl 5 typescript jestjs

这是同一个问题,这里正确回答了jest global variable example,但问题是 Typescript。

console.log(__DEV__);
Run Code Online (Sandbox Code Playgroud)

结果是:

console.log(__DEV__);
Run Code Online (Sandbox Code Playgroud)

全局变量__DEV__在 package.json 中定义为:

  "jest": {
    "globals": {
      "__DEV__": true
    }
  }
Run Code Online (Sandbox Code Playgroud)

有人有解决方案或解决方法吗?

相关笑话文档:https://jestjs.io/docs/en/next/configuration#globals-object

Jun*_*ndl 3

在 ts-jest 中,需要用“ts-jest”包装一些配置值:

  "jest": {
    "globals": {
      "ts-jest": {
        "__DEV__": true
      }
    }
  }
Run Code Online (Sandbox Code Playgroud)

并可以通过代码访问:

console.log((global as any).__DEV__
Run Code Online (Sandbox Code Playgroud)

在这里找到答案https://kulshekhar.github.io/ts-jest/docs/