And*_*man 6 javascript mocha.js node.js ecmascript-6
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
摩卡咖啡测试:
/* 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));
});
});
});
Run Code Online (Sandbox Code Playgroud)
我mocha
直接通过PowerShell控制台启动。结果:
JLR*_*she 25
Mocha从 7.1.0 版本开始支持 ESM(发布:2020 年 2 月 26 日)。
这需要 Node 12.11.0 或更高版本,并且受当前在 Node 中使用模块的限制/限制:
"type": "module"
的 package.json 中必须有import
从 CommonJS 模块导入时不能使用命名导入等等。
另一种选择是使用esm包,它不受上述限制:
mocha -r esm
Run Code Online (Sandbox Code Playgroud)
我个人的经验是,尝试利用 Mocha 新的、固有的 ESM 支持仍然是一个相当大的负担,但使用 esm 包是非常无缝的。
就我而言,运行:
npx mocha --require esm test_path/
Run Code Online (Sandbox Code Playgroud)
"scripts": {
// ...
"test": "npx mocha --require esm --reporter spec test_path/"
}
Run Code Online (Sandbox Code Playgroud)
"scripts": {
// ...
"test": "npx mocha --require esm --reporter spec test_path/"
}
Run Code Online (Sandbox Code Playgroud)
小智 -1
Babel 和 Browserfy 是可能的 https://drublic.de/blog/es6-modules-using-browserify-mocha/
归档时间: |
|
查看次数: |
7451 次 |
最近记录: |