Site icon DopeThemes

30 Days of JavaScript: Unit Testing in JavaScript — Day 15

30 Days of JavaScript: Building a Portfolio Website — Day 30

Welcome back, JavaScript enthusiasts! On Day 15 of our 30 Days of JavaScript series, we shift our focus to the critical practice of Unit Testing in JavaScript. Writing code is just one part of the development process—ensuring that code behaves as expected is equally important. This is where unit tests come into play, evaluating small, individual parts of the code, or “units,” for correctness.

Today, we’ll explore the importance of unit testing, introduce popular frameworks like Jest and Mocha, and dive into different levels of test cases—from beginner to advanced techniques. By mastering unit testing, you’ll catch bugs early, streamline development, and build a more reliable codebase.

Table of Contents

Why Unit Testing?

Unit testing is critical because it ensures that each part of your code functions as expected. Here are some key reasons to implement unit testing in your development workflow:

Jest and Mocha: Testing Frameworks in JavaScript

Two of the most popular frameworks for unit testing in JavaScript are Jest and Mocha. Let’s take a look at both.

Jest

Developed by Facebook, Jest is a powerful testing framework designed to work out of the box with minimal configuration. It’s known for its simplicity and features like snapshot testing and parallel test running.

Getting Started with Jest:

First, install Jest using npm:

npm install --save-dev jest

Here’s an example of a simple test using Jest:

/**
 * Simple test to check if 1 + 2 equals 3.
 * 
 * @returns {void}
 */
test('adds 1 + 2 to equal 3', () => {
  expect(1 + 2).toBe(3);
});

Run your tests with:

npm run test
Mocha

Mocha is another flexible testing library widely used for unit testing in JavaScript. Unlike Jest, Mocha allows you to choose your preferred assertion library, such as Chai.

Getting Started with Mocha:

You can install Mocha using npm:

npm install --save-dev mocha

Here’s an example of a simple test using Mocha:

/**
 * Basic test using Mocha and the assert library.
 * 
 * @returns {void}
 */
var assert = require('assert');
describe('Simple Test', function() {
  it('should return -1 when the value is not present', function() {
    assert.equal([1, 2, 3].indexOf(4), -1);
  });
});

Run the tests with:

npm run test

Writing and Running Test Cases

Writing test cases involves creating scenarios to ensure that your code behaves as expected. Let’s walk through examples for different levels of expertise.

Beginner Level Example:

Here’s a simple function that adds two numbers:

/**
 * Function to add two numbers.
 * 
 * @param {number} a - First number.
 * @param {number} b - Second number.
 * @returns {number} The sum of a and b.
 */
function add(a, b) {
  return a + b;
}

Test this function using Jest:

/**
 * Test case for add function to check if 3 + 7 equals 10.
 * 
 * @returns {void}
 */
test('adds 3 + 7 to equal 10', () => {
  expect(add(3, 7)).toBe(10);
});
Intermediate Level Example:

For more complexity, consider a function that filters out negative numbers from an array:

/**
 * Function to filter negative numbers from an array.
 * 
 * @param {Array<number>} numbers - The array of numbers.
 * @returns {Array<number>} The filtered array with non-negative numbers.
 */
function filterNegative(numbers) {
  return numbers.filter(number => number >= 0);
}

Test this function using Mocha and Chai:

/**
 * Mocha test case for filterNegative function.
 * 
 * @returns {void}
 */
var expect = require('chai').expect;
describe('Filter Negative Numbers', function() {
  it('should filter out negative numbers', function() {
    var numbers = [-1, 2, -3, 4];
    var result = filterNegative(numbers);
    expect(result).to.eql([2, 4]);
  });
});

Advanced Unit Testing Techniques

Unit testing isn’t just about writing simple tests—it’s about mastering advanced techniques like mocking, spying, and stubbing. These techniques make it possible to test more complex scenarios, such as API calls or asynchronous code.

Example Using Jest and Mocking:

Here’s an example of mocking a function with Jest:

/**
 * Mocking fetchData function in Jest.
 * 
 * @returns {void}
 */
jest.mock('fetchData');
test('fetches data', () => {
  const data = 'some data';
  fetchData.mockResolvedValueOnce(data);
  expect(fetchData()).resolves.toBe(data);
});

In this example, Jest mocks the fetchData function to control its return value during testing, allowing you to simulate how the function behaves without making an actual API call.

Conclusion

Today, on Day 15, we explored the world of Unit Testing in JavaScript. Starting from the basics of why unit testing is critical, we introduced popular frameworks like Jest and Mocha, walked through simple and complex test cases, and explored advanced techniques such as mocking.

By integrating unit testing into your development process, you’ll be able to write code with confidence, catch issues early, and ensure that your code remains reliable and maintainable as it grows. Testing isn’t just about catching bugs; it’s about building trust in your codebase, allowing you to scale and innovate with fewer obstacles.

Unit testing is a valuable skill for any developer, and as you continue practicing, you’ll find that testing becomes an essential part of writing clean, robust JavaScript code. Remember, testing isn’t just a task—it’s a mindset that ensures your code is as solid as the logic it follows.

What’s Next?

In Day 16, we’ll explore Web Components and Custom Elements. You’ll learn how these modern web technologies allow developers to build reusable, encapsulated components that work across frameworks. Get ready to explore the future of web development!

Next: 30 Days of JavaScript: Web Components and Custom Elements — Day 16

Exit mobile version