无法使用打字稿设置玩笑

时间:2019-09-08 03:36:55

标签: typescript jestjs ts-jest

我正在按照以下示例为打字稿项目设置一些基本的单元测试: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)

这是带有完整示例的公共仓库:https://gitlab.com/opensas/jest-typescript

有人能指出我正确的方向,还是提供一个可行的例子?

3 个答案:

答案 0 :(得分:1)

以下是jestjstypescript的演示用途:https://github.com/mrdulin/jest-codelab

devDependencies of package.json

"jest": "^24.8.0",
"ts-jest": "^24.0.2",
"typescript": "^3.5.3"

在项目的根路径中,创建jest.config.js

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node'
};

这就是全部设置。您可以在此处找到文档并按照以下4个步骤操作:https://github.com/kulshekhar/ts-jest#getting-started

答案 1 :(得分:1)

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.

答案 2 :(得分:0)

问题在于,尝试使用以下命令后,我的配置文件为jest.config.ts

npx jest --config jest.config.ts
Usage: jest.js [--config=<pathToConfigFile>] [TestPathPattern]
[...]
The --config option requires a JSON string literal, or a file path with a .js or .json extension.
Example usage: jest --config ./jest.config.js

我刚刚将jest.config.ts重命名为jest.config.js,一切正常...

-

我可以在@shadowspan和@ slideshowp2帮助下解决它,谢谢!