带有mocha的Typescript-不能在模块外使用import语句



我试图做一个简单的测试来了解使用mocha的单元测试。

文件夹结构

  • 节点模块
  • package.json
  • package-lock.json
  • testA.ts
  • testA.spec.ts
  • tsconfig.json

tsconfig.json

{
"compilerOptions": {    
"target": "ES2019",    
"module": "commonjs",
"rootDir": "./",
"moduleResolution": "node",
"allowJs": false,
"declaration": false,
"outDir": "./dist",
"esModuleInterop": false,
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitAny": false,
"noImplicitThis": true,
"alwaysStrict": true,
"skipLibCheck": true
},
"exclude": [
"node_modules"
]
}

package.json

{
"name": "unittest",
"version": "1.0.0",
"description": "",
"main": "index.js",
"type": "module",
"scripts": {
"test": "mocha",
"build": "rm -rf dist && tsc"
},
"author": "",
"license": "ISC",
"devDependencies": {
"@types/chai": "^4.2.22",
"@types/jest": "^27.0.3",
"@types/mocha": "^9.0.0",
"@types/sinon": "^10.0.6",
"chai": "^4.3.4",
"mocha": "^9.1.3",
"nyc": "^15.1.0",
"sinon": "^12.0.1",
"typescript": "^4.5.2",
"ts-node": "^10.4.0"
},
"mocha": {
"check-leaks": true,
"globals": [
"crypto"
],
"recursive": true,
"spec": [
"./*.ts"
]
}
}

测试A.spec.ts

import * as chai from 'chai'
const expect = chai.expect
describe('First Test', () => {
it('should run the test', () => {
const a = 12
expect(a).to.be.equal(12)

})
})

当我运行npm test时,我会得到以下错误。

/home/user/dev/unitTest/node_modules/@babel/core/src/config/files/index browser.ts:1从"导入类型{Handler};gensync">

SyntaxError:无法在模块之外使用导入语句

尝试了我在互联网上搜索到的一切,但仍然无法解决这个问题。

我找到了解决方案。在package.json内部,我添加了对摩卡的需求

"devDependencies":{...},
"mocha": {
"require": [
"support/ts-node-register.js"
],

ts节点寄存器.js

const tsNode = require('ts-node');
tsNode.register({
files: true,
});

最新更新