📝 Step 1: What is Jest?

Jest is a JavaScript testing framework designed to make it easy to write and run tests. It was developed by Facebook and is used in major applications like React, Node.js, Twitter, Spotify, and Airbnb. It is one of the most popular testing frameworks today due to its speed, simplicity, and ease of setup.

Jest allows you to test JavaScript code without requiring a browser, making it perfect for both front-end and back-end testing.

⁉️ How to Install Jest

🔰 To start using Jest in your project, follow these steps:

  1. Initialize your Node.js environment by running:

    npm init
  2. Install Jest by running:

    npm install --save-dev jest@26.6.3
  3. After installation, verify that Jest is working by running:
    npm test

    You should see a message saying “no tests found,” which means Jest is set up correctly and ready to run your tests.


🔧 Step 2: Anatomy of a Test Suite

In Jest, tests are organized into describe blocks. Each test is written inside a test block or an it block. These blocks help you organize your tests in a clear and readable structure.

🔰 Example Test Structure:

describe('Calculator Test', () => {
  describe('Addition Function', () => {
    test('should return 42 when adding 20 and 22', () => {
      expect(addition(20, 22)).toBe(42);
    });
  });
});

🔰 Key Elements:

  • describe: Groups related tests together, making them easy to manage.
  • test or it: Defines the actual test. You describe what the function should do and pass a function that contains the expectations.
  • expect: The Jest assertion function that checks the value returned by the function.

🛠️ Step 3: Writing Our First Test

Let’s apply Test-Driven Development (TDD) principles by writing a test for a simple addition function in a calculator.

1️⃣First: Set Up Directories

  • Create a 📂scripts directory and a 📂tests directory.
  • In 📂scripts, create a file called 📄calc.js
  • in 📂tests, create a file called 📄calc.test.js.

Set Up Directories for JavaScript test by Jest

2️⃣Second: Write the Test

In 📄calc.test.js, write the following test:

const addition = require('../scripts/calc'); // Import the function

describe('Calculator Test', () => {
  describe('Addition Function', () => {
    test('should return 42 when adding 20 and 22', () => {
      expect(addition(20, 22)).toBe(42);
    });
  });
});

3️⃣Third: Write Just Enough Code

Now, define the addition function in 📄calc.js to make the test pass:

function addition(a, b) {
  return 42;
}
module.exports = addition;

Run the tests by typing:

npm test

If the test passes, you’ve successfully written and run your first test!


🔄 Step 4: Breaking Our Test

Now that our first test is passing, let’s break it by adding a new test to check another calculation.

1️⃣First: Add New Test

In calc.test.js, add a new test to check the sum of 42 + 31:

test('should return 73 when adding 42 and 31', () => {
  expect(addition(42, 31)).toBe(73);
});

Run the tests again using npm test. The second test will fail because the addition function currently only returns 42.

2️⃣Second: Fix the Test

Update the addition function to handle all cases correctly:

function addition(a, b) {
  return a + b;
}
module.exports = addition;

Now, both tests should pass.


⚙️ Step 5: Mocking in Jest

When testing JavaScript, you often need to interact with external systems like DOM elements or APIs. Directly testing these systems in a real browser can be inefficient and unnecessary. Mocking allows you to simulate these external systems, enabling you to test your JavaScript code in isolation.

⁉️ What is jsdom?

Jest uses a mock DOM called jsdom. This is a simulated environment that mimics the browser’s DOM, allowing you to test JavaScript code that interacts with HTML elements without needing to load a real webpage.

🔰 Example: Testing DOM Interactions

Let’s walk through an example where we simulate a button click that changes the content of a paragraph.

1️⃣ Set Up the Mock DOM with beforeEach:

We use beforeEach() to set up a fresh mock DOM for each test. This ensures we start with a clean slate every time a test is run.

beforeEach(() => {
  document.body.innerHTML = `
    <button id="myButton">Click me</button>
    <p id="par"></p>
  `;
});
    • ⁉️ Explanation: We’re creating a simple mock HTML structure with:

      • A button with the ID myButton.
      • A paragraph with the ID par.

This mock DOM will simulate what you would typically have on an actual webpage.

2️⃣ Simulate the Button Click and Test the Change:

Next, we simulate the user clicking the button and check if the paragraph text updates as expected.

test('should change paragraph text when button is clicked', () => {
  const button = document.getElementById('myButton');
  const para = document.getElementById('par');

  button.addEventListener('click', () => {
    para.innerHTML = 'You clicked!';
  });

  button.click();  // Simulate the click event

  expect(para.innerHTML).toBe('You clicked!');
});
    • ⁉️ What’s happening here:

      • We get references to the button and paragraph using getElementById.
      • We add an event listener to the button so that when it’s clicked, it updates the paragraph’s content to ‘You clicked!’.
      • We simulate the button click with button.click().
      • Finally, we use expect() to check if the paragraph’s content changed to the expected value, ‘You clicked!’.

3️⃣ Running the Test:

Once you’ve written the test, run it with the command:

npm test

Jest will simulate the DOM and run your test. If the test passes, it means the content of the paragraph was correctly updated when the button was clicked.

⁉️ Why Mocking Matters:

Mocking with jsdom allows you to test JavaScript interactions with HTML elements in isolation, without needing a browser. This makes your tests faster, more reliable, and easier to manage, especially when testing more complex DOM manipulations or user interactions.

You can extend this approach to test things like:

  • User input (e.g., entering text into form fields).
  • Changing multiple DOM elements at once.
  • Simulating events like click, submit, keydown, etc.

🧪 Step 6: Testing the DOM by Jest

What if you want to test multiple DOM elements? You can load the entire HTML page into Jest’s mock DOM using the fs module.

Example: Test the Presence of <h1> Tag

const fs = require('fs');

beforeEach(() => {
  const fileContents = fs.readFileSync('index.html', 'utf-8');
  document.body.innerHTML = fileContents;
});

test('should find h1 tag in loaded HTML', () => {
  const h1 = document.getElementsByTagName('h1');
  expect(h1.length).toBe(1);
});

This test checks if an <h1> tag exists in the loaded HTML.


🎥 Video Tutorial for JavaScript test by Jest

The included a video link help you better understand Jest Test. This video from Web Dev Simplified provides a step-by-step guide, making it easier to grasp the concepts of testing and how to implement Jest in your projects.


🎓 Conclusion: Mastering Jest for JavaScript Testing

Jest is an excellent framework for writing and running automated tests in JavaScript. Whether you’re testing functions, mocking the DOM, or performing full integration tests, Jest has the tools to help you write clean, reliable, and maintainable tests.

By following Test-Driven Development (TDD) principles, using mocking, and testing the DOM effectively, you can ensure your JavaScript code works as expected.