[英]Mocha / Webpack: Cannot use import statement outside a module
I'm new to Node and JS Testing.我是 Node 和 JS 测试的新手。 I have a web applications w/ Webpack as a bundler.我有一个 web 应用程序 w/ Webpack 作为捆绑器。 I have some entry point JS's which are included into the page.我有一些包含在页面中的入口点 JS。 The entry points are using module files like this:入口点使用这样的模块文件:
export default function() {
...
}
Now I would like to Unit test this module.现在我想对这个模块进行单元测试。 I have picked up Mocha but it is not critical to me.我已经拿起摩卡,但它对我来说并不重要。 Could be Jest or anything else.可能是 Jest 或其他任何东西。
I wrote a very simple test.js
like this.我像这样写了一个非常简单的test.js
It it not doing anything but tests if the entire setup works:它除了测试整个设置是否有效外什么都不做:
import foo from '../js/someModuleOfMine'
const assert = require('assert')
describe('Test Suite', () => {
it('should at least run', () => {
assert.equal(true, true)
})
})
executing mocha
from CLI gives me this error:从 CLI 执行mocha
给我这个错误:
import foo from '../js/someModuleOfMine'
^^^^^^
SyntaxError: Cannot use import statement outside a module
Adhering to some advises I have tired to add "type": "module"
to my package.json
but it only changed error to something even more obscure:遵循一些建议,我已经厌倦了将"type": "module"
添加到我的package.json
,但它只是将错误更改为更加模糊的内容:
Error: Not supported
I am definitely missing something obvious but I cannot comprehend what.我肯定遗漏了一些明显的东西,但我无法理解是什么。
Not sure if it will help the OP, but I had the same problem and it was due to typescript. I solved in this way:不确定它是否对 OP 有帮助,但我遇到了同样的问题,这是由于 typescript 造成的。我这样解决了:
install ts-node:安装 ts 节点:
npm install ts-node --save-dev
add the require
line in the mocha config (I have it in the package.json, but one can also have it in the.mocharc.json file):在 mocha 配置中添加require
行(我在 package.json 中有它,但也可以在 .mocharc.json 文件中有它):
"mocha": {
"spec": "./**/*test.ts",
"ignore": "./node_modules/**",
"require": "ts-node/register/files",
"timeout": 20000
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.