简体   繁体   English

是否可以在 Mocha 测试中使用 ES6 模块?

[英]Is it possible to use ES6 modules in Mocha tests?

ES6, Windows 10 x64, Node.js 8.6.0, Mocha 3.5.3 ES6、Windows 10 x64、Node.js 8.6.0、摩卡 3.5.3

Is it possible to use ES6 modules in Mocha tests?是否可以在 Mocha 测试中使用 ES6 模块? I have the problems with export and import keywords.我有exportimport关键字的问题。

/* 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;
        }
    }
}

Mocha test:摩卡测试:

/* 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));
    });
  });
});

I launch the mocha directly through the PowerShell console.我直接通过 PowerShell 控制台启动mocha The result:结果:

在此处输入图像描述

Mocha has support for ESM from version 7.1.0 onward (release: Feb. 26, 2020). Mocha 从 7.1.0 版本开始支持 ESM (发布:2020 年 2 月 26 日)。

This requires Node 12.11.0 or higher, and is subject to the current restrictions/limitations of using modules in Node:这需要 Node 12.11.0 或更高版本,并且受当前在 Node 中使用模块的限制/限制:

  • Either you must use .mjs file extensions for source files that use ES modules, or you must have "type": "module" in your package.json对于使用 ES 模块的源文件,您必须使用 .mjs 文件扩展名,或者您的 package.json 中必须有"type": "module"
  • You can't use named imports when import ing from CommonJS modules从 CommonJS 模块导入时不能使用命名import

And so on.等等。

Another option is to use the esm package, which is not subject to the above limitations:另一种选择是使用esm包,它不受上述限制:

mocha -r esm

My personal experience as of yet is that trying to take advantage of Mocha's new, inherent ESM support is still a considerable burden, but using the esm package is quite seamless.我个人的经验是,尝试利用 Mocha 新的、固有的 ESM 支持仍然是一个相当大的负担,但使用 esm 包是非常无缝的。

In my case run with:在我的情况下运行:

basic comand:基本命令:

npx mocha --require esm test_path/

package.json包.json

"scripts": {
    // ...
    "test": "npx mocha --require esm --reporter spec test_path/"
}

Runing跑步

npm test

Regarding your main question关于你的主要问题

Is it possible to use ES6 modules in Mocha tests?是否可以在 Mocha 测试中使用 ES6 模块?

Yes, as of Mocha version 9 :是的,从Mocha 版本 9开始:

Mocha is going ESM-first! Mocha 将以 ESM 为先! This means that it will now use ESM import(test_file) to load the test files, instead of the CommonJS require(test_file) .这意味着它现在将使用 ESM import(test_file)来加载测试文件,而不是 CommonJS require(test_file) This is not a problem, as import can also load most files that require does.这不是问题,因为 import 也可以加载require加载的大多数文件。 In the rare cases where this fails, it will fallback to require(...) .在极少数情况下失败,它将回退到require(...) This ESM-first approach is the next step in Mocha's ESM migration, and allows ESM loaders to load and transform the test file.这种 ESM 优先的方法是 Mocha 的 ESM 迁移的下一步,它允许 ESM 加载程序加载和转换测试文件。

You also need to use a Node version which supports import , which would be >= 13.2.0您还需要使用支持importNode版本,即>= 13.2.0


Regarding the Unexpected token import problem - others here wrote good answers, but here's a better answer from another related question:关于Unexpected token import问题 - 这里的其他人写了很好的答案,但这是另一个相关问题的更好答案:

How does mocha / babel transpile my test code on the fly? mocha / babel 如何即时转换我的测试代码?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM