Almost every module that we use in NodeJS, need to be imported in some way. These modules offer functions that we can use. However, I have noticed that testing frameworks like mocha and jest dont seem to work the same way. You just include "mocha" or "jest" under the "test" script in package.json, and it does all the work.

I am very curious as to how this works. How can we make a script / function execute just by mentioning a keyword under "scripts" in package.json.

Would be very helpful if someone can answer this! :)

1 Answers

2
Tim Wong On

The keyword mocha is actually a CLI, just like ls and cat if you use linux.

If you are asking for how to build a CLI with Node.js, the following references might help.

How mocha works

By default, mocha looks for the glob "./test/*.js", so you may want to put your tests in test/ folder. If you want to include subdirectories, pass the --recursive option.

Reference: https://mochajs.org/#the-test-directory

  1. Run the mocha CLI.
  2. The program sets the global variables (e.g. describe, it, etc.).
  3. The program loads all javascript files under the test directory.