【发布时间】:2018-03-11 06:27:54
【问题描述】:
ES6、Windows 10 x64、Node.js 8.6.0、Mocha 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。结果:
【问题讨论】:
-
我认为关键是 Node 8.6 支持导入/导出而无需转译。但是,我不确定 mocha 是否允许使用它所需的
--experimental-modules,因此可能仍然需要转译,直到它这样做(或直到支持使其稳定) -
我认为这不是重复的问题。顶级浏览器原生支持 ES 模块,可以run Mocha tests without using Babel。
-
时间已经过去,现在可以在 mocha 中使用 import 语法,这要感谢 esm 模块。将其添加到您的依赖项中,然后使用
mocha -r esm。你甚至不需要切换到.mjs扩展。 -
这个问题实际上不是 stackoverflow.com/questions/46255387/… 的重复,因为后者是关于 Babel,而这个问题不是。
标签: javascript node.js ecmascript-6 mocha.js