我正在按照此示例为 typescript 项目设置一些基本单元测试:https://dev.to/muhajirdev/unit-testing-with-typescript-and-jest-2gln
我有一个 main.ts
导出 isInternalLink
功能
和一个 main.spec.ts
试图测试它
但我收到以下错误:
C:\data\devel\apps\tmp\jest-typescript\src\main.spec.ts:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import { isInternalLink } from './main.js';
SyntaxError: Unexpected token {
at ScriptTransformer._transformAndBuildScript (node_modules/@jest/transform/build/ScriptTransformer.js:537:17)
这是带有完整示例的公共(public)存储库:https://gitlab.com/opensas/jest-typescript
任何人都可以指出我正确的方向,或提供一个有效的例子吗?
最佳答案
Jest TypeScript documentation涵盖使用 babel 预处理 TypeScript 文件,还链接到 ts-jest
.
添加 ts-jest到您的项目,安装 ts-jest
:
npm install --save-dev ts-jest
并将其添加到您的 package.json 以预处理 TypeScript 文件:
"jest": {
"transform": {
"^.+\\.tsx?$": "ts-jest"
},
"moduleFileExtensions": [
"ts",
"tsx",
"js",
"jsx",
"json"
]}
在您的项目中执行此操作后,我能够运行测试:
$ npx jest
PASS src/main.spec.ts
✓ should return false given external link (2ms)
✓ should return true given internal link
Test Suites: 1 passed, 1 total
Tests: 2 passed, 2 total
Snapshots: 0 total
Time: 1.096s, estimated 2s
Ran all test suites.
关于typescript - 无法使用 typescript 设置 Jest ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57839008/