Mocha + TypeScript:不能在模块外使用 import 语句

Mocha + TypeScript: Cannot use import statement outside a module

我正在观看 this video 以了解如何向我的 Express 路线添加一些简单的测试,但我在执行测试时遇到了各种错误。错误是:

import * as chai from 'chai';

^^^^^^

SyntaxError: Cannot use import statement outside a module

我已经阅读了一些类似的 Stack Overflow 问题和 GitHub 问题,但我没有找到适合我自己的应用程序的解决方案。最后我在 GitHub 上找到了关于 ES 模块的 Mocha documentation 但它没有用:

我使用 TypeScript 和 CommonJS 模块创建应用程序进行转译,因此我将 "test": "env TS_NODE_COMPILER_OPTIONS='{\"module\": \"commonjs\" }' mocha src/test/*.ts" 添加到 package.json 脚本,但我每次都遇到相同的错误。我正在使用 ts-node 作为服务器。

无论如何,这是我的 tsconfig.json 文件:

{
    "compilerOptions": {
        "sourceMap": true,
        "target": "es6",
        "module": "commonjs",
        "outDir": "./dist",
        "rootDir": "./src"
    },
    "exclude": [
        "node_modules"
    ]
}

这是 src/test/mi-route.ts 文件:

import * as chai from 'chai';
import * as chaiHttp from 'chai-http';
import server from '../app';

// Assertions
chai.should();

chai.use(chaiHttp);

describe('API Users', () => {
    // Test Route GET
    describe('GET /api/admin/users', () => {
        it('Should return all the users', done => {
            chai.request(server)
                .get('/api/admin/users')
                .end((err, response) => {
                    response.should.have.status(200);
                    response.body.should.be.a('object');
                    done();
                });
        });
    });
});

这是我的 package.json 脚本:

"scripts": {
    "dev": "ts-node-dev src/app.ts",
    "start": "node dist/app.js",
    "test": "env TS_NODE_COMPILER_OPTIONS='{\"module\": \"commonjs\" }' mocha src/test/*.ts",
    "build": "tsc -p"
  },

所以...有什么建议吗?我应该更改 Common JS 模块吗?提前致谢

感谢 @types/chai-http – 无法使用 ES6 导入 GitHub 问题的答案。

我添加了第二个 TypeScript 配置文件 tsconfig.testing.json,其中包含以下信息:

{
    "compilerOptions": {
      "module": "commonjs",
      "target": "es2015",
      "lib": ["es2017"],
      "declaration": false,
      "noImplicitAny": false,
      "removeComments": true,
      "inlineSourceMap": true,
      "moduleResolution": "node"
    },
    "include": ["scripts/**/*.ts", "src/**/*.ts", "node_modules/lodash-es/**/*.js"]
  }

然后我将 package.json 脚本更改为:

"test": "env TS_NODE_PROJECT=\"tsconfig.testing.json\" mocha --require ts-node/register 'src/test/**/*.ts'",

最后我将测试文件更改为:

import * as chai from 'chai';
import 'chai-http';
import server from '../app';

// Assertions
chai.should();

chai.use(require('chai-http'));

嗯,运行 测试现在有效。

遇到了同样的问题,差点放弃将 Mocha 与 TypeScript 结合使用(在我们的案例中 Angular 9)。

这对我有帮助:

tsconfig.json中:

替换为:

"module": "esnext", 

有了这个:

"module": "commonjs",

我还在这里找到了一个使用 TypeScript 的 Mocha 的工作示例,并使用那里的 tsconfig 文件与我的进行比较: https://medium.com/@RupaniChirag/writing-unit-tests-in-typescript-d4719b8a0a40

我最近在一个项目中遇到过几次这个问题。

该项目包含许多较小的模块,这些模块都是用 TypeScript 编写的,并在提交前进行了编译。我已经(显然至少有几次 link 已经是紫色了)以某种方式设法在不编译的情况下提交我的模块。当 mocha 尝试执行未提交到版本控制的 .js 版本的依赖项时,这会导致错误。

构建依赖项、提交和更新包解决了我的问题。希望这可以帮助其他人与我处于相似的位置!

此错误的另一个可能原因:

您的文件类型是 .tsx 而不是 .ts 吗?将其更改为 .ts 将修复错误或添加对 .tsx 文件的适当支持。

也有这个问题,发现我不必切换到 commonJS,只需要启用 ESM:

npm install --save-dev esm

./node_modules/mocha/bin/mocha -r esm -r ts-node/register "src/**/*Test.ts"

确保您的项目中有 .mocharc.json

{
  "extension": ["ts"],
  "timeout": 5000,
  "exit": true,
  "require": "ts-node/register"
}

(另见 https://github.com/mochajs/mocha-examples/tree/master/packages/typescript#es-modules