JS Guide
HomeQuestionsSearchResources
Search

Built for developers preparing for JavaScript, React & TypeScript interviews.

ResourcesQuestionsSupport
HomeQuestionsSearchProgress
HomeQuestionstesting
Prev
testing
senior
methodology

What is TDD and how does it compare to BDD?

tdd
bdd
test-driven
methodology
cucumber
Quick Answer

TDD (Test-Driven Development) writes tests before code in a red-green-refactor cycle. BDD (Behavior-Driven Development) extends TDD with natural language specifications focusing on behavior from user's perspective. TDD is developer-focused; BDD involves stakeholders.

Detailed Explanation

TDD Process:

  1. Red: Write failing test
  2. Green: Write minimal code to pass
  3. Refactor: Improve code, tests still pass

TDD Benefits:

  • Forces clear requirements thinking
  • Ensures testable design
  • Documents behavior through tests
  • Builds confidence in refactoring

BDD Process:

  1. Write specifications in Given-When-Then
  2. Stakeholders can read/write specs
  3. Specifications become tests

Key Differences:

  • TDD: Technical, code-focused
  • BDD: Behavioral, user-focused
  • BDD uses ubiquitous language
  • BDD better for collaboration

Code Examples

TDD cycle example
// TDD: Red -> Green -> Refactor

// Step 1: RED - Write failing test first
describe('ShoppingCart', () => {
  test('adds item to empty cart', () => {
    const cart = new ShoppingCart();
    cart.addItem({ id: 1, name: 'Widget', price: 10 });
    expect(cart.items).toHaveLength(1);
    expect(cart.total).toBe(10);
  });
});
// Test fails - ShoppingCart doesn't exist

// Step 2: GREEN - Minimal code to pass
class ShoppingCart {
  constructor() {
    this.items = [];
  }
  
  get total() {
    return this.items.reduce((sum, item) => sum + item.price, 0);
  }
  
  addItem(item) {
    this.items.push(item);
  }
}
// Test passes!

// Step 3: REFACTOR - Improve while tests pass
// Add more tests, refine implementation
test('increases quantity for existing item', () => {
  const cart = new ShoppingCart();
  cart.addItem({ id: 1, name: 'Widget', price: 10 });
  cart.addItem({ id: 1, name: 'Widget', price: 10 });
  expect(cart.items).toHaveLength(1);
  expect(cart.items[0].quantity).toBe(2);
});
// RED - need to update implementation...

Resources

Test Driven Development

article

Cucumber.js

docs

Related Questions

How do you design a testing strategy for a large application?

senior
strategy

What is the difference between unit tests and integration tests?

mid
integration
Previous
What is visual regression testing and how do you implement it?