Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does "npm" run "npm test"?

Tags:

node.js

npm

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?

like image 222
Vitalii Korsakov Avatar asked Nov 23 '13 15:11

Vitalii Korsakov


People also ask

How does npm test work?

The command knows which test suite to specify based on which value it finds corresponding to the “test” key in “scripts”. We can set up our own tests in our environment by specifying a "test" : "file/path" key/value pair in "scripts"once we have a package. json file for our project.

Is it npm test or npm run test?

TL;DR there is no difference. It's just a shortcut for npm tests which run the test command in the package. json file. npm run test performs the same action in this case.

What is Test command npm?

The test command is the command that is run whenever you call npm test . This is important when integrating with continuous integration/continuous deployment tools (such as jenkins , codeship , teamcity ).


1 Answers

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.

like image 54
Sam Mikes Avatar answered Oct 18 '22 22:10

Sam Mikes