Mocha无法找到正在测试的模块的依赖关系

时间:2016-09-17 21:04:12

标签: javascript node.js ecmascript-6 mocha

鉴于这个ES6类,我依赖于一个名为xethya-random-mtw的公开注册包:


// /src/Dice.js

import MersenneTwister from 'xethya-random-mtw';

class Dice {

  constructor(faces) {
    if (typeof faces !== 'number') {
      throw new Error('Dice#constructor: expected `faces` to be a Number.');
    }

    if (faces < 2) {
      throw new Error('Dice#constructor: A dice must have at least two faces.');
    }

    this.faces = faces;
  }

  roll() {
    const mt = new MersenneTwister();
    return Math.ceil(mt.generateRandom() * this.faces);
  }

}

export default Dice;

我想用Mocha运行以下测试:


// /test/DiceSpec.js

import { expect } from 'chai';
import Dice from '../src/Dice';

describe('Dice', () => {

  describe('#constructor', () => {
    it('should instantiate a Dice with the expected input', () => {
      const dice = new Dice(2);
      expect(dice.faces).to.equal(2);
    });
    it('should fail if a single-faced Dice is attempted', () => {
      expect(() => new Dice(1)).to.throw(/at least two faces/);
    });
    it('should fail if `faces` is not a number', () => {
      expect(() => new Dice('f')).to.throw(/to be a Number/);
    });
  });

  describe('#roll', () => {
    it('should roll numbers between 1 and a given number of faces', () => {
      const range = new Range(1, 100 * (Math.floor(Math.random()) + 1));
      const dice = new Dice(range.upperBound);
      for (let _ = 0; _ < 1000; _ += 1) {
        const roll = dice.roll();
        expect(range.includes(roll)).to.be.true;
      }
    });
  });
});

当我运行npm run test mocha --compilers js:babel-register时,我收到以下错误:


$ npm run test 

> xethya-dice@0.0.0 test /Users/jbertoldi/dev/joel/xethya-dice
> mocha --compilers js:babel-register

module.js:442
    throw err;
    ^

Error: Cannot find module 'xethya-random-mtw'
    at Function.Module._resolveFilename (module.js:440:15)
    at Function.Module._load (module.js:388:25)
    at Module.require (module.js:468:17)
    at require (internal/module.js:20:19)
    at Object. (/Users/jbertoldi/dev/joel/xethya-dice/src/Dice.js:9:1)
    ...

为什么不能正确解析此依赖关系?

1 个答案:

答案 0 :(得分:2)

看起来像xethya-random-mtw包中的问题。在这个包的package.json中,您有"main": "index.js"而index.js文件不存在,因此无法解析。 main应包含一些真实路径,例如"main": "dist/index.js"