Chuck's Academy

Testing JavaScript and DOM with Jest

Installation and Configuration of Jest

Getting Ready to Use Jest: Installation and Configuration

In this section, we will learn how to install Jest and configure it properly to start writing and running tests in our JavaScript projects.

Prerequisites

Before continuing, make sure you have Node.js and npm (Node Package Manager) installed on your system. You can download and install Node.js from here.

Installing Jest

To install Jest, you can use npm. Open your terminal or command line and navigate to your project directory. Then, run the following command to install Jest as a development dependency:

bash

Alternatively, if you prefer to use yarn, you can install Jest with the following command:

bash

Basic Jest Configuration

Once Jest is installed, it's advisable to add test scripts in your package.json file to facilitate running the tests. Open package.json and add the following script in the "scripts" section:

json

This will allow you to run Jest using the command:

bash

Test File Structure

It is a good practice to keep the tests in a separate directory or follow a specific naming convention to differentiate them from the source code. Some common conventions include:

  • Placing the test files in a __tests__ directory.
  • Naming the test files with the same name as the file they are testing, followed by .test.js or .spec.js.

For example:

Advanced Jest Configuration

Jest allows for extensive configuration through a jest.config.js file or directly in the package.json. Here is an example of a basic configuration in jest.config.js:

javascript

Configuration in package.json

You can also configure Jest directly in your package.json:

json

Complete Configuration Example

Below is a complete example that includes installation, configuration, and a basic test case to ensure Jest is working correctly.

  1. Initialize a new project:
bash
  1. Install Jest:
bash
  1. Configure Jest in package.json:
json
  1. Create directory and file structure:
  1. Write the function code to be tested in sum.js:
javascript
  1. Write the unit test in sum.test.js:
javascript
  1. Run the tests:
bash

[Jest will search for and execute all defined tests, producing a detailed report with the results].


With Jest installed and configured, we are ready to start writing our first unit tests. In the next section, we will explore how to write and run unit tests with Jest. Continue to deepen your testing experience with Jest!


Ask me anything