【发布时间】:2021-12-30 05:15:52
【问题描述】:
我正在尝试做一个简单的测试来了解使用 mocha 的单元测试。
文件夹结构
- node_modules
- 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"
]
}
}
testA.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 从“gensync”导入类型{处理程序};
^^^^^^SyntaxError: 不能在模块外使用 import 语句
尝试了我在互联网上搜索的所有内容,但仍然无法解决这个问题。
【问题讨论】:
-
您已经安装
ts-node,但看不到使用它:mochajs.org/#-require-module-r-module -
嗨@jonrsharpe。不幸的是,添加
--require ts-node/register不会改变结果。 -
添加它where,但是?您是否将您的设置与链接的工作 TypeScript Mocha 设置进行了比较?给一个minimal reproducible example - 我从你发布的内容中得到那个错误in
testA.spec.ts,如果我使用"require": ["ts-node/register"],它就会消失。 -
@jonrsharpe 我添加到我的测试脚本中。然后我从mochajs/mocha-examples 复制了
.mocharc.yaml。现在我得到TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" -
那么请edit 更新您的问题minimal reproducible example。
标签: javascript node.js typescript unit-testing mocha.js