Why I can't run the same command that is my script of package.json without calling the script?

Why I can't run a command exactly the same as it is in my package.json file? Here is an example:

Package.json

"scripts": {
  ...
  "test": "jest",
  ...
},

If I run "npm run test" jest works fine and my unit tests are executed. But if I try to run jest without using the script in the package.json, I can't execute it.

When I run the command jest:

zsh: command not found: jest

I thought that when I'm at the directory of the project, I would be able to use the same scripts as the project, without having to add it to the scripts and calling it via npm or yarn.


Solution 1:

Actually, if you can't use jest by typing it's name, it's mean that jest is locally added, you can run locals commands from two ways, one with ./node_modules/.bin/jest wich will invoke the jest command, and the second, npx jest wich will invoke jest too. For the script field, As explained in the npm documentation:

If you depend on modules that define executable scripts, like test suites, then those executables will be added to the PATH for executing the scripts.

So, when you execute npm run test, npm will update your path to access to jest which is exported into the node_modules/.bin directory on npm install.