javascript - 错误 : cannot find module when testing with mocha

标签 javascript node.js ecmascript-6 babeljs

我正在使用 babeljs 编写一个 RPG 引擎库。我有两个文件:

dice.js

import assert from 'assert';
import Random from 'random-js';

export default class Dice {
  constructor(maxNumber) {
    assert(typeof(maxNumber) === "number", "maxNumber must be a number");

    this._mt = Random.engines.mt19937();
    this.minNumber = 1;
    this.maxNumber = maxNumber;
  }

  makeThrow() {
    this._mt.autoSeed();
    return Random.integer(this.minNumber, this.maxNumber)(this._mt);
  }
}

throwManager.js

import assert from 'assert';
import Dice from 'dice';
export default class ThrowManager {
  constructor(settings) {
    assert(settings.hasOwnProperty("numberOfDices"), "must set 'numberOfDices'");
    assert(settings.hasOwnProperty("maxNumberInDice"), "must set 'maxNumberInDice'");
    assert(settings.maxNumberInDice <= 1, "must have at least 1 dice");
    this.settings = settings;
  }
  execute() {
    var throwResults = [];
    for (var d = 1; d <= this.settings.numberOfDices; d++) {
      var dice = new Dice(this.settings.maxNumberInDice);
      throwResults.push(dice.makeThrow());
    };
    return throwResults;
  }
}

当我用 mocha 测试它们时,我做了这些导入:

tests.js

var assert = require('assert');
var Amzhen = require('../Amzhen.js');
var random = require('random-js');
//tests here...

然而,当我运行测试时,我得到了这个:


Error: Cannot find module 'dice'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/home/joel/Amzhen.js/Amzhen.js:47:28)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at Object.<anonymous> (/home/joel/Amzhen.js/test/tests.js:2:14)

为什么找不到 dice 模块有什么想法吗?

我正在使用 babel src --out-file Amzhen.js && mocha 编译代码

最佳答案

你应该使用:

import Dice from './dice';

'dice' 不是已发布、已安装的 Node.js 模块的名称,而是本地文件,因此您应该使用带有适当路径的 ./dice .

另见 Module not found error in node.js

关于javascript - 错误 : cannot find module when testing with mocha,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28931904/

相关文章:

javascript - MongoDB:获取数组的计数

javascript - Node.js 中间件内部的异步调用?

node.js - 使用 typescript 和 Node 热重载

javascript - 单击 React Native 中的项目时如何关闭模式并从 flatlist 返回值?

javascript - 在 JavaScript ES6 类中无限期调用 "set function()"

javascript - 如何从 `result1` 返回不在 result2 数组中的对象数组?

javascript - 如何有效地将 javascript 链接到 html?

javascript - 有条件地将类添加到特定元素

javascript - 从后面的代码运行 JavaScript 代码到 updatePanel

javascript - 如何使用 Angularjs 和 NodeJs 在 ckeditor 中上传图像