node.js “npm”如何运行“npm test”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20164398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How does "npm" run "npm test"?
提问by Vitalii Korsakov
I always thought that npm testcommand just launches what I would write in package.jsoninside scripts: { test: ...}section. But I have this weird bug when it doesn't work.
我一直认为该npm test命令只是启动我将在package.json内部scripts: { test: ...}部分编写的内容。但是当它不起作用时我有这个奇怪的错误。
So, I have this piece of config in package.json
所以,我有这个配置 package.json
"scripts": {
"start": "node index.js",
"test": "mocha tests/spec.js"
}
When I try to run tests I type npm testin terminal and had this error:
当我尝试运行测试时,我npm test在终端中输入并出现此错误:
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?
但是当我输入 just 时一切正常mocha tests/spec.js。任何想法为什么会这样?
UPDATE:
更新:
I've tried to install commander and I had an error Cannot find module 'glob'. After installing globI have
我试过安装commander,但出现错误Cannot find module 'glob'。安装后glob我有
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?
但实际上问题是为什么我会出现这些错误,为什么在运行时一切正常mocha tests/spec.js?
回答by Sam Mikes
You may have two versions of mocha installed: one globally (npm install -g mocha) and one locally, which appears to be broken.
您可能安装了两个版本的 mocha:一个是全局的 ( npm install -g mocha),另一个是本地的,看起来已经损坏了。
When you run a script through npm, either as npm run-script <name>or with a defined shortcut like npm testor npm start, your current package directory's bindirectory 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 mochaexecutable script.
当您通过或使用定义的快捷方式(如或 )运行脚本时npm,当前包目录的目录将放置在路径的前面。对于您的包,可能是,其中包含指向包的可执行脚本的链接。npm run-script <name>npm testnpm startbin./node_modules/.bin/mocha
You can probably fix this by removing the local mocha and reinstalling it with --save-dev:
您可以通过删除本地 mocha 并使用 --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.
这应该会为您提供安装了所有依赖项(指挥官等)的 mocha 的本地工作副本。

