【发布时间】:2020-07-14 13:20:49
【问题描述】:
我正在观看 this video 以了解如何向我的 Express 路由添加一些简单的测试,但是在执行测试时我遇到了各种错误。错误是:
从'chai'导入*作为chai;
^^^^^^
SyntaxError: 不能在模块外使用 import 语句
我已经阅读了一些类似的 Stack Overflow 问题和 GitHub 问题,但我没有为我自己的应用程序找到解决方案。最后我在 GitHub 上找到了Mocha documentation 关于 ES 模块的信息,但是没有用:
我使用 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 模块吗?提前致谢
【问题讨论】:
-
也许您应该使用
ts-mocha而不是mocha来运行测试?
标签: javascript node.js typescript ecmascript-6 mocha.js