Vitalii Korsakov
Vitalii Korsakov

Reputation: 47636

How does "npm" run "npm test"?

I always thought that npm test command just launches what I would write in package.json inside scripts: { test: ...} section. But I have this weird bug when it doesn't work.

So, I have this piece of config in package.json

"scripts": {
  "start": "node index.js",
  "test": "mocha tests/spec.js"
}

When I try to run tests I type npm test in terminal and had this error:

module.js:340
    throw err;
          ^
Error: Cannot find module 'commander'

But everything is OK when I type just mocha tests/spec.js. Any ideas why is that?

UPDATE:

I've tried to install commander and I had an error Cannot find module 'glob'. After installing glob I have

Error: Cannot find module '../'**

But actually question is why do I have these errors and why is everything OK when running mocha tests/spec.js?

Upvotes: 44

Views: 123742

Answers (1)

Sam Mikes
Sam Mikes

Reputation: 10828

You may have two versions of mocha installed: one globally (npm install -g mocha) and one locally, which appears to be broken.

When you run a script through npm, either as npm run-script <name> or with a defined shortcut like npm test or npm start, your current package directory's bin directory is placed at the front of your path. For your package that's probably ./node_modules/.bin/, which contains a link to your package's mocha executable script.

You can probably fix this by removing the local mocha and reinstalling it with --save-dev:

rm -rf node_modules/mocha
npm install --save-dev mocha

That should get you a working local copy of mocha with all its dependencies (commander etc.) installed.

Upvotes: 29

Related Questions