Open oldoc63 opened 2 years ago
Before writing any test you'll need to use Node.js and npm to set up a JavaScript project and install Mocha.
Mocha is one of those packages and is used to test other JavaScript code
A JavaScript project is a directory of files. The following command creates a file package.json that can be used to manage packages for the project.
npm init
After running this command you will be prompted to enter information about your project. It's okay to skip some fields if you're not ready to enter that information.
With your project setup, you can install packages.
npm install mocha -D
Here's what this command means:
Once you npm install packages, you can find the packages and all their dependencies in the node_modules folder. The new directory structure contains the following:
project |_ node_modules | .bin | mocha |__ ... | package.json
The ... in the file structure represents other packages that are a dependency for Mocha. Initialize the project:
npm init
Install Mocha:
npm install mocha -D
You can view package.json in the text editor. You can now see mocha as a dependency.
After installing Mocha as a dependency we can run it in two ways. The first (and more tedious) method is to call it directly from node_modules:
./node_modules/mocha/bin/mocha
The second (and recommended) method is to add a script to package.json. In the scripts object in package.json, set the value of "test": "mocha". It should look like this:
"scripts": {
"test": "mocha"
}
Now you can call Mocha with the following command:
npm test
Instead of manually running each test in the test directory, you can use this command to run the full test suite automatically.
Testing is an essential part of development. When used properly, testing can catch and identify issues with your implementation code before you deploy it to users. Instead of testing every function manually, developers automate their tests with a test framework. Developers use test frameworks to organize and automate tests that provide useful feedback when errors occur. We will use the Mocha test framework to write tests against JavaScript methods. We'll learn: