【问题标题】:How do I use a Native Node JS Module (--experimental-modules) with Mocha如何在 Mocha 中使用 Native Node JS 模块(--experimental-modules)
【发布时间】:2018-12-06 14:40:40
【问题描述】:

我有以下测试套件...

import Mocha from 'mocha';
import path from 'path';
const __dirname = path.dirname(new URL(import.meta.url).pathname);
(()=>{
    let mocha = new Mocha();
    mocha.addFile(path.resolve(__dirname,'./tests/sampleTest.js'));
    mocha.run(failures => {
        console.log("Running Mocha");

        process.on('exit', () => {
            console.log("Ending Mocha");
            process.exit(failures ? 1 : 0);
        });
    });
})();

还有下面的测试文件……

const assert = require('assert');
describe('Array', function() {
  describe('#indexOf()', function() {
    it('should return -1 when the value is not present', function() {
      assert.equal([1,2,3].indexOf(4), -1);
    });
  });
});

这很好用,但是,我想将其转换为模块 JS (.mjs),以便在测试中导入其他模块。我通过更改扩展名并制作代码来尝试这个...

import assert from 'assert';
describe('Array', function() {
  describe('#indexOf()', function() {
    it('should return -1 when the value is not present', function() {
      assert.equal([1,2,3].indexOf(4), -1);
    });
  });
});

当我运行它时,我得到...

Must use import to load ES Module: **/src/test/js/webdriver/tests/sampleTest.mjs

我也试过像这样导入它......

import Mocha from 'mocha';
import path from 'path';
import './tests/sampleTest.mjs';
const __dirname = path.dirname(new URL(import.meta.url).pathname);
(()=>{
    let mocha = new Mocha();
//    mocha.addFile(path.resolve(__dirname,'./tests/sampleTest.mjs'));
    mocha.run(failures => {
        console.log("Running Mocha");

        process.on('exit', () => {
            console.log("Ending Mocha");
            process.exit(failures ? 1 : 0);
        });
    });
})();

然后我得到...

ReferenceError: 描述未定义

我也试过

import mocha from "mocha"
...
mocha.describe(...)

但这也没有用。

如何将另一个模块加载到 mocha 中?

【问题讨论】:

  • 再一次,我不想让 Babel 参与进来。使用 babel 超级简单
  • 这意味着我不需要为了运行测试而带回 es5 的额外步骤。我希望他们保持 es6+ 并使用本机模块加载器
  • 你可以在你的测试文件中尝试import { describe } from 'mocha'
  • 我试过了,但我忘记了错误,所以我会再试一次并发布

标签: javascript node.js ecmascript-6 mocha.js


【解决方案1】:

目前唯一的解决方法是https://www.npmjs.com/package/mjs-mocha

我希望此链接适用于此处,因为 npm 确实会永久保存包。请随意参考软件包文档和来源

【讨论】:

    猜你喜欢
    • 2020-02-15
    • 2018-07-18
    • 2021-03-30
    • 2019-11-03
    • 2019-11-05
    • 2023-01-18
    • 2015-10-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多