gpt4 book ai didi

javascript - 配置 Jest 以支持 Typescript (NodeJs)

转载 作者:行者123 更新时间:2023-11-30 13:55:13 26 4
gpt4 key购买 nike

我想为我的 Node/Express/Typescript 应用程序编写测试。在我的 src 目录旁边,我添加了一个 tests 目录,其中包含一个包含此演示内容的 app.spec.ts 文件

import { App } from '../src/app';

describe('App', () => {
let instance: App;

beforeEach(() => {
instance = new App();
});

it('creates an instance of App', async () => {
expect(instance).toBeInstanceOf(App);
});
});

不幸的是,Jest 无法处理 Typescript。

Details:

C:...\tests\app.spec.ts:1 ({"Object. ":function(module,exports,require,__dirname,__filename,global,jest){import { App } from '../src/app';

SyntaxError: Unexpected token { at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:471:17) at ScriptTransformer.transform (node_modules/@jest/transform/build/ScriptTransformer.js:513:25)

这是我的 package.json(相关字段)

{
"scripts": {
"start": "node dist/app.js",
"dev": "nodemon src/app.ts",
"build": "tsc -p .",
"test": "jest",
"testWithCoverage": "jest --coverage"
},
"devDependencies": {
"@types/express": "^4.17.0",
"@types/jest": "^24.0.17",
"@types/node": "^12.6.9",
"@typescript-eslint/eslint-plugin": "^1.13.0",
"@typescript-eslint/parser": "^1.13.0",
"eslint": "^5.16.0",
"eslint-config-airbnb-base": "^13.2.0",
"eslint-plugin-import": "^2.18.2",
"jest": "^24.8.0",
"nodemon": "^1.19.1",
"ts-jest": "^24.0.2",
"ts-node": "^8.3.0",
"typescript": "^3.5.3"
}
}

此外,我用该内容创建了一个 jest.config.js 文件

module.exports = {
roots: [
'./tests',
],
moduleFileExtensions: [
'ts',
'tsx',
'js',
'jsx',
],
};

有人知道这里缺少什么吗?

最佳答案

将您的 jest.config.js 文件更改为:

module.exports = {
"roots": [
"<rootDir>/src",
"<rootDir>/tests"
],
"transform": {
"^.+\\.tsx?$": "ts-jest"
},
}

关于javascript - 配置 Jest 以支持 Typescript (NodeJs),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57430978/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com