Test-Driven Development (TDD) is a software development process that emphasizes writing tests before writing actual code. It's a powerful technique for improving code quality, reducing bugs, and fostering a more robust development workflow.
In TDD, the cycle consists of three phases:
TDD can seem counterintuitive at first, but it offers significant advantages:
Before diving into TDD, you need a testing framework for JavaScript. Here are some popular choices:
We'll use Jest for this example. Follow these steps:
npm install --save-dev jest
      
        module.exports = {
          preset: 'ts-jest',
          testEnvironment: 'node',
          roots: ['/src'],
          testMatch: ['**/__tests__/**/*.+(ts|tsx|js)', '**/?(*.)+(spec|test).+(ts|tsx|js)'],
          transform: {
            '^.+\\.(ts|tsx)$': 'ts-jest'
          }
        };
         
      
        const sum = require('./sum');
        test('adds 1 + 2 to equal 3', () => {
          expect(sum(1, 2)).toBe(3);
        });
        
      npm test
      Let's illustrate TDD with a simple function that reverses a string.
    // reverseString.test.js
    const reverseString = require('./reverseString');
    test('reverses a string', () => {
      expect(reverseString('hello')).toBe('olleh');
    });
    
    When you run this test, it will fail because the `reverseString` function doesn't exist yet.
    // reverseString.js
    function reverseString(str) {
      return str.split('').reverse().join('');
    }
    module.exports = reverseString;
    
    Now, the test should pass, turning the indicator to green.
The current implementation is functional, but it could be more readable. Let's refactor it:
    // reverseString.js
    function reverseString(str) {
      let reversed = '';
      for (let i = str.length - 1; i >= 0; i--) {
        reversed += str[i];
      }
      return reversed;
    }
    module.exports = reverseString;
    
    Ensure that all tests still pass after the refactoring.
By consistently following this Red-Green-Refactor cycle, you can develop well-tested and reliable JavaScript code.