我观看 此视频 是为了了解如何向我的 Express 路线添加一些简单的测试,但我在执行测试时遇到了各种错误。错误是:
从“柴”导入 \* 作为柴;
^^^^^^
SyntaxError: 不能在模块外使用 import 语句
我已经阅读了一些类似的 Stack Overflow 问题和 GitHub 问题,但没有找到适合我自己的应用程序的解决方案。最后我在 GitHub 上找到了关于 ES 模块的 Mocha 文档,但它没有用:
我使用 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 模块吗?提前致谢
原文由 Maramal 发布,翻译遵循 CC BY-SA 4.0 许可协议
感谢 @types/chai-http – Can’t use ES6 import GitHub 问题的答案,我能够进行测试。
我添加了第二个 TypeScript 配置文件
tsconfig.testing.json
包含以下信息:然后我将
package.json
脚本更改为:最后我改变了测试文件,如:
好吧,现在可以运行测试了。