Labs ICT
Pro Login

Behavior-Driven Development

Testing that reads like English.

Behavior-Driven Development

BDD is like TDD but with a focus on how the code behaves from the user's perspective. Instead of writing tests for internal functions, you write tests that describe what the system should do.

If you have ever used describe/it/expect, you have already done BDD without knowing it. That structure is the foundation of behavior-driven testing.

Writing Behavior-Focused Tests

BDD tests read like requirements. They describe the expected behavior in plain English.


describe('Shopping Cart', () => {
  it('adds items to the cart', () => {
    const cart = new ShoppingCart();
    cart.addItem({ name: 'Shirt', price: 25 });
    expect(cart.items.length).toBe(1);
  });

  it('calculates the total price', () => {
    const cart = new ShoppingCart();
    cart.addItem({ name: 'Shirt', price: 25 });
    cart.addItem({ name: 'Pants', price: 40 });
    expect(cart.getTotal()).toBe(65);
  });

  it('removes items from the cart', () => {
    const cart = new ShoppingCart();
    cart.addItem({ name: 'Shirt', price: 25 });
    cart.removeItem('Shirt');
    expect(cart.items.length).toBe(0);
  });
});
    

Read those test names out loud. They sound like a conversation about what the cart should do. That is the power of BDD.

Given-When-Then

A common BDD structure is Given-When-Then. It sets up context, describes an action, and verifies the result.


describe('Login', () => {
  it('given valid credentials, when user logs in, then session is created', () => {
    const auth = new AuthService();
    const session = auth.login('alice', 'password123');
    expect(session).toBeDefined();
    expect(session.userId).toBe('alice');
  });

  it('given invalid credentials, when user logs in, then error is thrown', () => {
    const auth = new AuthService();
    expect(() => auth.login('alice', 'wrong')).toThrow('Invalid credentials');
  });
});
    

BDD with Jest

Jest already supports BDD style with describe, it, and expect. You do not need extra tools. Just write your tests with behavior in mind instead of implementation details.

Try it Yourself →

Key Takeaways

  • BDD focuses on testing behavior, not implementation details
  • Tests should read like plain English requirements
  • Given-When-Then is a common structure for behavior tests
  • Jest already supports BDD style with describe/it/expect
  • BDD tests are great for communicating with non-technical team members