简体   繁体   中英

Mocha can't find dependencies for a module being tested

Given this ES6 class, where I have a dependency to a publicly-registered package called 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;

I want to run the following tests with 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;
      }
    });
  });
});

When I run npm run test , which is mocha --compilers js:babel-register , I get the following error:


$ 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)
    ...

Why does this dependency not gets resolved correctly?

Looks like the problem in the xethya-random-mtw package. In the package.json of this package you have "main": "index.js" while the index.js file is not exist so cannot be resolved. main should contain some real path, eg "main": "dist/index.js" .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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