Jest 测试失败,出现 Unexpected token,预期为“;"; [英] Jest test fails with Unexpected token, expected ";"

查看:69
本文介绍了Jest 测试失败,出现 Unexpected token,预期为“;";的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Node project using Typescript and Jest. Currently I have this project structure

使用这个 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"
  }
}

我在我的测试目录中创建了一个测试文件

I created a test file in my tests directory

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

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

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

但不幸的是我遇到了语法错误

but unfortunately I get a syntax error

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

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

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

at my app variable. It seems the test runner is not able to understand Typescript code. How can I fix my configuration to support Typescript in test files for Jest?

推荐答案

尝试在 jest 配置中添加 typescript 扩展:

Try to add typescript extension in jest config :

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 配置:

And then load the jest config in your package.json test script :

"scripts": {
    "test": "jest --config ./jest.config.js",
    ...
  },

这篇关于Jest 测试失败,出现 Unexpected token,预期为“;";的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆