javascript - Jest 测试失败,出现意外 token ,预期为 ";"

标签 javascript node.js typescript jestjs

我有一个使用 Typescript 和 Jest 的 Node 项目。目前我有这个项目结构

enter image description here

有了这个tsconfig.json文件

  "compilerOptions": {
    "target": "ES2017",
    "module": "commonjs",
    "allowJs": true,
    "outDir": "dist",
    "rootDir": "src",
    "strict": true,
    "moduleResolution": "node",
    "esModuleInterop": true
  }

这个jest.config.js文件
module.exports = {
  clearMocks: true,
  coverageDirectory: "coverage",
  testEnvironment: "node",
};

这个package.json文件
{
  "scripts": {
    "start": "node dist/App.js",
    "dev": "nodemon src/App.ts",
    "build": "tsc -p .",
    "test": "jest"
  },
  "dependencies": {
    "commander": "^3.0.1"
  },
  "devDependencies": {
    "@types/jest": "^24.0.18",
    "@types/node": "^12.7.4",
    "jest": "^24.9.0",
    "nodemon": "^1.19.2",
    "ts-jest": "^24.0.2",
    "ts-node": "^8.3.0",
    "typescript": "^3.6.2"
  }
}

我在我的测试目录中创建了一个测试文件
import { App } from '../src/App';

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

  test('It runs a test', () => {
    expect(true).toBe(true);
  });
});

但不幸的是我得到一个语法错误

SyntaxError: C:...\tests\App.test.ts: Unexpected token, expected ";" (5:9)



在我的app多变的。似乎测试运行者无法理解 Typescript 代码。如何修复我的配置以在 Jest 的测试文件中支持 Typescript?

最佳答案

尝试在 jest config 中添加 typescript 扩展:

module.exports = {
  roots: ['<rootDir>'],
  transform: {
    '^.+\\.ts?$': 'ts-jest'
  },
  testRegex: '(/__tests__/.*|(\\.|/)(test|spec))\\.ts?$',
  moduleFileExtensions: ['ts', 'js', 'json', 'node'],
  collectCoverage: true,
  clearMocks: true,
  coverageDirectory: "coverage",
};

然后在你的 package.json 测试脚本中加载 jest 配置:
"scripts": {
    "test": "jest --config ./jest.config.js",
    ...
  },

关于javascript - Jest 测试失败,出现意外 token ,预期为 ";",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57921019/

相关文章:

javascript - 通天塔加载器 : Module build failed: SyntaxError: Deleting local variable in strict mode

javascript - 用于 res.send 的 Express.js 中间件,在每个 res.send() 上调用函数

javascript - Node JS - 在新进程中执行一串代码

css - 如何在 rollup 中生成 css 类型

typescript - 如何在带有 Typescript 的 VueJs watch 中使用 Lodash debounce

javascript - 如何检查是否加载了某个 extjs 面板

javascript - 如何让下落的div可点击?

javascript - 是否可以在任何现有的 onsubmit/submit 之前绑定(bind) submit() 函数?

javascript - 如何从 $cookies 获取对象?

c++ - 如何将带有缓冲区的对象从插件发送到 Node 线程安全?