【问题标题】:unit-tests SyntaxError: Unexpected token {单元测试语法错误:意外的令牌 {
【发布时间】:2020-02-04 18:06:07
【问题描述】:

我收到此错误:

D:\nginx\ibdrweb\webapps\ibdr-document-2\doc-app\sources\forms\dynamic-form\lus\lus.js:1
import { Tools } from "@ShareUtils/tools";
       ^

SyntaxError: Unexpected token {
    at Module._compile (internal/modules/cjs/loader.js:721:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)

当我尝试执行以下命令时:

ts-mocha -p doc-app/tests/tsconfig.json doc-app/tests/lus-tests.ts

此问题已在此处https://github.com/Microsoft/TypeScript/issues/26018 讨论并已关闭。 尝试在 tsconfig.json 更改 "module": "commonjs" 没有帮助。 很多人写道问题仍然存在

我的项目是这样的

|- doc-app
|    |- < many direcotiries used at tests.ts >
|    |- tests
|          lus-tests.ts
|          tsconfig.json
|
|- node_modules
|- tsconfig.json

注意:节点“v10.16.0”

tsconfig.json 在测试目录

{
  "compilerOptions": {
    "target": "es5",
    "declaration": true,
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "suppressImplicitAnyIndexErrors": true,
    "lib": ["es6", "dom"],
    "typeRoots": [
      "node_modules/@types"
    ]
 },
 "awesomeTypescriptLoaderOptions": {
   "useWebpackText": true,
    "useTranspileModule": true,
    "doTypeCheck": true,
    "forkChecker": true
 },
 "include": [
   "./"
 ],
 "exclude": [
   "node_modules"
 ]
}

package.json 的有用部分

"devDependencies": {
  "@types/chai": "4.1.7",
  "@types/mocha": "5.2.7",
  "@types/sinon": "7.0.13",
  ...
  "chai": "4.2.0",
  ...
  "mocha": "6.1.4",
  ...
  "sinon": "7.3.2",
  ...
  "ts-mocha": "6.0.0",
  "ts-node": "8.4.1",
  "typescript": "2.9.2", //if change it to "3.6.3" it dosen't help
}

如果我在 tsconfig.json 中指定“模块”:“exnext”,那么错误是

D:\nginx\ibdrweb\webapps\ibdr-document-2\doc-app\tests\lus-tests.ts:1
import "mocha";
       ^^^^^^^

SyntaxError: Unexpected string
    at Module._compile (internal/modules/cjs/loader.js:721:23)

注意: import { Tools } from "@ShareUtils/tools"; node_modules 中的模块“工具”

【问题讨论】:

  • 如果测试没有导入模块(这又依赖于 node_modules 中的其他模块),那么它运行没有错误。一旦出现指向 node_modules 的依赖项,就会生成“意外令牌”错误。问题是如何正确运行用 typescript 编写的单元测试,其中有来自 node_modules 的依赖项?

标签: javascript node.js typescript unit-testing mocha.js


【解决方案1】:

第一个错误是因为你的 JavaScript 没有被 TypeScript 编译。您需要allowJs 才能使该文件按预期工作。第二个错误是有道理的,当您从 CommonJS 更改模块输出时,node.js 不会理解您的 ES 模块代码。

【讨论】:

  • 通过第二个错误,我明白为什么会这样。我的 tconconfig.son 有选项“模块”:“commonjs”。该错误仅作为示例发布,带有“module”:“exnext”选项。第一个错误:一旦检测到 node_modules 依赖项,就会发生编译错误。在被测模块中,有很多依赖引用了node_modules
猜你喜欢
  • 2019-03-27
  • 2016-10-31
  • 1970-01-01
  • 1970-01-01
  • 2019-10-28
  • 2019-01-17
  • 1970-01-01
  • 1970-01-01
  • 2017-10-07
相关资源
最近更新 更多