DEV Community

Cover image for Quick Guide for Following TDD in Node.js TypeScript
Tyler Steck
Tyler Steck

Posted on

Quick Guide for Following TDD in Node.js TypeScript

Suppose we are building a function that calculates the area of a rectangle. We'll start by writing a test for the function:

import { calculateRectangleArea } from './rectangle';

describe('calculateRectangleArea', () => {
  it('should correctly calculate the area of a rectangle', () => {
    const area = calculateRectangleArea(3, 4);
    expect(area).toBe(12);
  });
});
Enter fullscreen mode Exit fullscreen mode

This test should fail initially, since we haven't yet written the function calculateRectangleArea. Next, we'll write the function to make the test pass:

export function calculateRectangleArea(width: number, height: number): number {
  return width * height;
}
Enter fullscreen mode Exit fullscreen mode

Now that the test passes, we can move on to writing additional tests to ensure that the function works correctly in other cases. For example:

describe('calculateRectangleArea', () => {
  it('should correctly calculate the area of a rectangle', () => {
    const area = calculateRectangleArea(3, 4);
    expect(area).toBe(12);
  });

  it('should return 0 if either width or height is 0', () => {
    const area1 = calculateRectangleArea(0, 5);
    const area2 = calculateRectangleArea(3, 0);
    expect(area1).toBe(0);
    expect(area2).toBe(0);
  });

  it('should throw an error if either width or height is negative', () => {
    expect(() => calculateRectangleArea(-1, 5)).toThrow();
    expect(() => calculateRectangleArea(3, -2)).toThrow();
  });
});

Enter fullscreen mode Exit fullscreen mode

By following the TDD process, we have ensured that our code is thoroughly tested, and that it meets the requirements specified by the tests. We can be confident that the code is correct and maintainable, and that it will work as expected in a variety of situations.

Top comments (0)