我当时正在看这个视频 https://www.youtube.com/watch?v=I4BZQr-5mBY为了学习如何向我的 Express 路线添加一些简单的测试,但我在执行测试时遇到各种错误。错误是:
从 'chai' 导入 * 作为 chai;
^^^^^^
语法错误:无法在模块外部使用 import 语句
我读过一些类似的 Stack Overflow 问题和 GitHub 问题,但没有找到适合我自己的应用程序的解决方案。最后我发现摩卡文档 https://github.com/mochajs/mocha-examples/tree/master/packages/typescript#es-modules在 GitHub 上查看了有关 ES 模块的信息,但没有成功:
我使用 TypeScript 和 CommonJS 模块来创建应用程序来进行转译,所以我添加了"test": "env TS_NODE_COMPILER_OPTIONS='{\"module\": \"commonjs\" }' mocha src/test/*.ts"
to the package.json
脚本,但我每次都会遇到相同的错误。我在用ts-node
作为服务器。
无论如何,这是我的tsconfig.json
file:
{
"compilerOptions": {
"sourceMap": true,
"target": "es6",
"module": "commonjs",
"outDir": "./dist",
"rootDir": "./src"
},
"exclude": [
"node_modules"
]
}
这就是src/test/mi-route.ts
file:
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 模块吗?提前致谢