【问题标题】:Mocha not understanding TypeScript "implements" keyword, giving SyntaxError: "... Unexpected token, expected {"Mocha 不理解 TypeScript “implements”关键字,给出 SyntaxError: “... Unexpected token, expected {”
【发布时间】:2018-09-07 19:40:12
【问题描述】:

我只是希望能够使用 ES6 在 TypeScript 中运行 Mocha 测试(我使用 npm 安装 mocha、ts-node 和 babel-core 包)。

我的 mocha 命令和产生的错误,下面是相关代码 sn-ps。请注意,ES6 似乎不是这里的问题,但 TypeScript 的“implements”关键字才是问题所在:

$ mocha -r babel-core/register -r ts-node/register model/piece/test/bishoptest.ts

/Users/$USER/projects/chess/node_modules/babylon/lib/index.js:4454
  var err = new SyntaxError(message);
            ^
SyntaxError: /Users/$USER/projects/chess/model/piece/src/bishop.ts: Unexpected token, expected { (4:28)
  2 | import {PieceHelper} from './piecehelper';
  3 | 
> 4 | export default class Bishop implements Piece {
    |                             ^

我在 bishoptest.ts 中的代码:

import { GameState, initialGameState } from '../../gamestate';
import Bishop from '../src/bishop';

import { expect } from 'chai';
import 'mocha';

describe('a bishop test', () => {
  // setup omitted...
  const bishop = new Bishop();
  const res = bishop; // do something (omitted...)
  it('should work', () => {
    expect(res).to.eql(false);
  });
});

我在 bishop.ts 中出现 SyntaxError 的代码:

import {Piece, Box} from './piece';
import {PieceHelper} from './piecehelper';

export default class Bishop implements Piece {
  // omitted...
}

顺便说一句,这里有更多信息: 在我运行mocha 命令的根文件夹中,我还有一个.babelrc 文件:

{
    "presets": ["es2015"]
}

我还有一个tsconfig.json,也在我调用mocha的根目录中:

{
    "compilerOptions": {
        "module": "es6",
        "target": "es6",
        "allowJs": true,
        "removeComments": true,
        "preserveConstEnums": true,
        "sourceMap": true
    },
    "include": [
        "**/src/*",
        "**/test/*"
    ],
    "exclude": [
        "node_modules",
        "**/*.spec.ts"
    ]
}

【问题讨论】:

  • Piece 是类还是接口?请张贴代码。

标签: typescript mocha.js babeljs ts-node babel-core


【解决方案1】:

更新:奇怪!我将 class 更改为 interface 并且 implements 关键字现在可以使用以下相同的点。下面是截图:

请注意屏幕截图中的不同断言错误消息!哈哈!

如果上面更新的部分适合你,那么请告诉我,我会相应地编辑下面的部分。


我没有使用 implements 关键字,而是使用相同的代码使用 extends 关键字,并在本地安装了 .ts 扩展名和 typescript [--save-dev],并为 @987654330 使用了 --compilers 开关选项@喜欢这样

mocha --compilers ts-node\register bishoptest.ts

它可以工作,但我将Piece 用作类而不是接口。看看是不是你要找的。​​p>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-20
    • 2019-08-05
    • 2017-03-31
    • 2018-08-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多