使用.ts文件(TypeScript)配置Jest全局测试设置 [英] Configure Jest global tests setup with .ts file (TypeScript)
问题描述
我正在使用ts-jest(Jest和TypeScript),并希望进行配置 所有测试套件的一些全局设置(初始化测试数据库).
I am using ts-jest (Jest and TypeScript) and want to configure some global setup for all test suites (initialize test database).
我发现在玩笑配置中有globalSetup
个选项:
I found that there is globalSetup
options in jest configuration:
"jest": {
"globalSetup": "./jest-config.js"
}
,但仅.js
文件可用于设置.我想使用.ts
文件,因为我的所有代码
包括用于在TypeScript中设置的代码.
but only .js
file can be used for setup. I want to use .ts
file because all my code
including code for setup in TypeScript.
我该如何实现?
推荐答案
我找到了解决方案.
我最初的项目结构是:
.
|--src
| |--service.ts
|--tests
| |--service.test.ts
|--dist
|--tsconfig.json
|--package.json
package.json中的最佳配置:
Jest configuration in package.json:
"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"
}
使用此配置ts-jest
在.ts文件的内存转储中执行.
我的tsconfig.json
的compilerOptions
中有outDir
选项,但是在outDir中没有任何内容,因为我无法使用已编译的jest-config.js
With this configuration ts-jest
perform in memory transpiling of the .ts files.
I have outDir
option in compilerOptions
of my tsconfig.json
, but nothing is written in that outDir and because I cann't use transpiled jest-config.js
然后我将src中的tests文件夹移动到Jest配置中并更改. 该项目的新结构为:
Then I move tests folder in src and change Jest config. New structure of the project is:
.
|--src
| |--service.ts
| |--tests
| |--service.test.ts
| |--jest-config.ts
|--dist
|--tsconfig.json
|--package.json
新笑话配置为:
"jest": {
"globalSetup": "./dist/tests/jest-config.js",
"moduleFileExtensions": ["ts", "js", "json"],
"testMatch": [
"**/dist/**/*.test.js"
],
"testEnvironment": "node"
}
现在我可以在jest中使用jest-config.js进行全局设置了.
Now I can use jest-config.js for global setup in Jest.
添加
-
Jest设置文件(在我的示例中为jest-config.js)必须导出一个异步函数:
Jest setup file (in my example jest-config.js) must export one async function:
module.exports = async function() { ... }
在运行测试之前,您需要编译.ts源文件.
Before running the tests, you need to compile source .ts files.
这篇关于使用.ts文件(TypeScript)配置Jest全局测试设置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!