[英]Is it possible to use ES6 modules in Mocha tests?
ES6、Windows 10 x64、Node.js 8.6.0、摩卡 3.5.3
是否可以在 Mocha 测试中使用 ES6 模块? 我有export
和import
关键字的问题。
/* eventEmitter.js
*/
/* Event emitter. */
export default class EventEmitter{
constructor(){
const subscriptions = new Map();
Object.defineProperty(this, 'subscriptions', {
enumerable: false,
configurable: false,
get: function(){
return subscriptions;
}
});
}
/* Add the event listener.
* @eventName - the event name.
* @listener - the listener.
*/
addListener(eventName, listener){
if(!eventName || !listener) return false;
else{
if(this.subscriptions.has(eventName)){
const arr = this.subscriptions.get(eventName);
arr.push(listener);
}
else{
const arr = [listener];
this.subscriptions.set(eventName, arr);
}
return true;
}
}
/* Delete the event listener.
* @eventName - the event name.
* @listener - the listener.
*/
deleteListener(eventName, listener){
if(!eventName || !listener) return false;
else{
if(this.subscriptions.has(eventName)){
const arr = this.subscriptions.get(eventName);
let index = arr.indexOf(listener);
if(index >= 0){
arr.splice(index, 1);
return true;
}
else{
return false;
}
}
else{
return false;
}
}
}
/* Emit the event.
* @eventName - the event name.
* @info - the event argument.
*/
emit(eventName, info){
if(!eventName || !this.subscriptions.has(eventName)) {
return false;
}
else{
for(let fn of this.subscriptions.get(eventName)){
if(fn) fn(info);
}
return true;
}
}
}
摩卡测试:
/* test.js
* Mocha tests.
*/
import EventEmitter from '../../src/js/eventEmitter.js';
const assert = require('assert');
describe('EventEmitter', function() {
describe('#constructor()', function() {
it('should work.', function() {
const em = new EventEmitter();
assert.equal(true, Boolean(em));
});
});
});
我直接通过 PowerShell 控制台启动mocha
。 结果:
在我的情况下运行:
npx mocha --require esm test_path/
"scripts": {
// ...
"test": "npx mocha --require esm --reporter spec test_path/"
}
npm test
可以使用 Babel 和 Browserfy https://drublic.de/blog/es6-modules-using-browserify-mocha/
关于你的主要问题
是否可以在 Mocha 测试中使用 ES6 模块?
Mocha 将以 ESM 为先! 这意味着它现在将使用 ESM
import(test_file)
来加载测试文件,而不是 CommonJSrequire(test_file)
。 这不是问题,因为 import 也可以加载require
加载的大多数文件。 在极少数情况下失败,它将回退到require(...)
。 这种 ESM 优先的方法是 Mocha 的 ESM 迁移的下一步,它允许 ESM 加载程序加载和转换测试文件。
您还需要使用支持import
的Node版本,即>= 13.2.0
关于Unexpected token import
问题 - 这里的其他人写了很好的答案,但这是另一个相关问题的更好答案:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.