5. Node Modules & Testing
In this lesson we'll learn the history of Node and the fundamentals of using Node Modules to build JavaScript programs.
Table of Contents:
Summary
Node is a "JavaScript runtime environment" which is just a fancy way to say it is a program for running JavaScript.
A module is a file containing code, which can then be imported and utilized in other parts of a larger program or system.
In a Node project, a file exports a module by assigning a value to
module.exports.It can export one value/function (a single "default export").
It can export many values/functions (a group of "named exports").
A module can be imported with the
require(filename)function.
Third-party modules can be downloaded from the Node Package Manager (NPM) online registry.
When a module is downloaded, it is listed as a dependency in
package.jsonand added to thenode_modulesfolder.package.jsonis a file with meta-data about a Node project including dependencies and configuration.Developer dependencies are dependencies used by the developer(s) who created the package but aren't needed by the users of the package. They are not added to the
node_modulesfolder.
JavaScript Object Notation (JSON) is a file format for representing data in an JavaScript-Object-like notation with key:value pairs.
Jest is an npm module that provides functions for creating automated tests.
Test-Driven Development is a style of programming in which tests are created first and steer the functionality to be built.
What is Node?
JavaScript started out as a language that could only be used to create programs that ran in the browser. Server-side code (the code running on the computer that sends the website to your browser) had to be written in another language, such as PHP or Java.
In 2009, the Node Runtime Environment (or simply "Node") was invented to allow programmers to create server-side programs with JavaScript, thus opening the door for fullstack JavaScript development.
To run a JavaScript program using Node, we use the terminal command node <file_name>:

You can also use the node command on its own to open the Node read-evaluate-print-loop (REPL) which can be useful for testing expressions:

Modules
Consider the simple JavaScript program below. It declares a few functions for calculating data about a circle with a given radius and then prints them out. Notice that the main function is where the functions are all being executed in a logical order:
As a project grows in scale and complexity, separation of concerns becomes increasingly important.
To achieve separation of concerns, JavaScript projects are typically separated into multiple files called modules that share code with each other.
A module is a file containing code, which can then be imported and utilized in other parts of a larger program or system.
Exporting with module.exports (CommonJS)
module.exports (CommonJS)In a Node project, a module exports its code by assigning one or more values to the .exports property of the module object—module.exports.
When module.exports is assigned a single value/function, we call that a default export:
You will also commonly see module.exports assigned an object containing multiple values/functions. These are called named exports:
Importing with require() (CommonJS)
require() (CommonJS)To import a module's values, use the require(filepath) function. The filepath should point to the module you want to import.
Destructuring Shorthand
If the module exports an object...
...we typically will destructure the object immediately upon importing it:
Node Package Manager (NPM)
Suppose you wanted to add functionality that allows you to get command-line input from user of your program via the terminal. Do you have the tools to implement that feature on your own?
While you could figure this out, there is no need to reinvent the wheel! Instead, just download an existing module from the Node Package Manager (NPM) online registry.
Visit https://www.npmjs.com/ to explore available packages. Start by searching up the "prompt-sync" package.

Installing and Using Dependencies from NPM
To install any module from npmjs, use the npm install (or npm i) command in your Terminal:
Now, you should see a node_modules/ folder with a prompt-sync/ folder inside. Open up the prompt-sync/index.js file to see the module that is exported!
To use the package in our own program, use require() again, this time with just the name of the module. Our program will know to look at the nearest node_modules folder for it.
We can now use the prompt function in our code to add user input functionality!
Dependencies, package.json, and node_modules
package.json, and node_modulesWhen you download a package from NPM, it is called a dependency.
Every dependency of a project, and its version number, will be listed in the file package.json (if the file doesn't exist, the npm i command will create it). The existence of this file turns our project into a package.

The downloaded module will be placed in a node_modules/ folder along with any sub-dependencies that the module itself may require.
You can see the sub-dependencies of a module by opening its own package.json file. All modules listed under "dependencies" will also be installed in node_modules/.
In
prompt-sync/package.json, we can see it hasstrip-ansias a dependency.In
strip-ansi/package.json, we can see it hasansi-regexas a dependency.

Developer Dependencies
In the prompt-sync/package.json file, you will notice that prompt-sync-history is listed under "devDependencies".
Developer dependencies are dependencies used by the developer(s) who created the package but aren't needed by the users of the package. They are not added to the
node_modulesfolder of the user.
One developer dependency that we will commonly use is the nodemon module. Install it using npm and the --save-dev flag to mark it as a developer dependency:
You should see nodemon added to the "devDependencies" section of your package.json (version numbers may vary):
The nodemon module provides a new terminal command nodemon that can be used to run a JavaScript file in "hot reload" mode. This means that any time you save a file in the project, it will re-run the file.
Jest Module and Testing
Tests are an essential part of professional software development. Without testing our code, we run the risk of deploying code with unexpected bugs. With testing, we are forced to think critically about how we expect our program to behave and then write our code to satisfy those tests.
The process of first writing tests and then writing code to satisfy those tests is called Test-Driven Development (TDD).
At Marcy, we use the Node module Jest to write automated tests for coding assignments.
Automated tests are JavaScript files that:
Import functions from source code
Run those functions with various inputs
Compare the returned values against the expected values.
A Jest test is written in a file ending in .spec.js or .test.js and looks like this:
To run these automated tests, use the command:
When tests fail, you will see the following output:

The test output provides some really useful information.
We can see which tests failed
For each failing test, we can see which
expect()statement failedWe can see what the expected value is (
12.566...) and what our function actually returned (undefined).
Armed with this information, we can more confidently build our functions knowing that we have a specific set of targets to aim for. Automated tests allow us to repeatedly run our code against the same set of tests until all expectations are met.
Challenge: Write tests for the getDiameter and getCircumference functions. Consider how you might test certain edge cases such as "bad" or missing inputs.
NPM Tips and Tricks
Here are a few useful tips and tricks for using npm like a pro!
package.json Scripts
package.json ScriptsYou can add a "scripts" section to the package.json file to make it easier to run commonly used Terminal commands.
To use these commands, we can type npm run script_name:
npm init -y
npm init -yWhen working on a new Node project, it is common to set up the package.json file prior to installing any dependencies.
This can be done using the command npm init which will ask you some questions to generate a package.json file.
You can also run npm init -y to skip the questions and build a package.json file using default values.
Madlib Challenge
A program is considered hard-coded if the program code must be modified in order to produce a new result.
The prompt-sync function is really useful for creating programs that will produce new results depending on the user's input.
In the madlib-challenge/index.js file you will find the following hard-coded program:
Your goal is to do the following in the madlib-challenge folder:
Download the
prompt-syncmodule usingnpm i prompt-syncImport and configure the
promptfunction inindex.jsReplace the hard-coded variables defined in the
mainfunction with values retrieved from the user via thepromptfunction.Re-organize the code such that the
madlibfunction is in its own file calledmadlib.jsthat exportsmadlibas the default export.
If you get stuck, you can view the solution below:
Last updated