使用.ts文件(TypeScript)配置Jest全局测试设置

Ale*_*kii 13 typescript jestjs

我正在使用ts-jest(Jest和TypeScript),并希望为所有测试套件配置一些全局设置(初始化测试数据库).

我发现globalSetupjest配置中有选项:

"jest": {
    "globalSetup": "./jest-config.js"
}
Run Code Online (Sandbox Code Playgroud)

但只有.js文件可用于设置.我想使用.ts文件,因为我的所有代码都包括在TypeScript中进行设置的代码.

我怎样才能做到这一点?

rem*_*eus 18

全局设置是在 ts 环境可用之前执行的,因此解决方法是通过在文件开头要求ts-node来手动创建环境。

在你的笑话配置中(package.jsonjest.config.js):

"globalSetup": "./globalSetup.ts"
Run Code Online (Sandbox Code Playgroud)

然后在globalSetup.ts

require('ts-node/register');

const setup = (): void => {
  // whatever you need to setup globally
};

export default setup;
Run Code Online (Sandbox Code Playgroud)

您可以在github上阅读有关ts-node的更多信息。


Ale*_*kii 9

我找到了解决方案.

我最初的项目结构是:

.
|--src
|  |--service.ts
|--tests
|  |--service.test.ts
|--dist
|--tsconfig.json 
|--package.json
Run Code Online (Sandbox Code Playgroud)

package.json中的Jest配置:

"jest": {
  "globals": {
    "ts-jest": {
      "tsConfigFile": "tsconfig.json"
    }
  },
  "moduleFileExtensions": ["ts","js"],
  "transform": {
    "^.+\\.(ts|tsx)$": "./node_modules/ts-jest/preprocessor.js"
  },
  "testMatch": [
    "**/tests/**/*.test.(ts|js)"
  ],
  "testEnvironment": "node"
}
Run Code Online (Sandbox Code Playgroud)

使用此配置ts-jest在内存中执行.ts文件的转换.我可以outDir选择compilerOptions我的tsconfig.json,但是没有写在outDir中,因为我不能使用transiled jest-config.js

然后我在src中移动tests文件夹并更改Jest配置.该项目的新结构是:

.
|--src
|  |--service.ts
|  |--tests
|     |--service.test.ts
|     |--jest-config.ts
|--dist
|--tsconfig.json 
|--package.json
Run Code Online (Sandbox Code Playgroud)

新的Jest配置是:

"jest": {
  "globalSetup": "./dist/tests/jest-config.js",
  "moduleFileExtensions": ["ts", "js", "json"],
  "testMatch": [
    "**/dist/**/*.test.js"
  ],
  "testEnvironment": "node"
}
Run Code Online (Sandbox Code Playgroud)

现在我可以在Jest中使用jest-config.js进行全局设置.

加成

  • Jest安装文件(在我的示例中为jest-config.js)必须导出一个异步函数:

    module.exports = async function() { ... }

  • 在运行测试之前,您需要编译源.ts文件.

  • ts-jest项目中有关此问题的问题:https://github.com/kulshekhar/ts-jest/issues/411 (2认同)
  • 谢谢 - 原生 jest+typescript 支持很糟糕。该解决方案将所有内容都转换为 .js,然后利用 jest。我花了几个小时试图解决 ts-jest 和 babel crap 的问题。这个解决方案有效!谢谢你! (2认同)