Labs ICT
Pro Login

describe() & it()

Organizing your tests properly.

describe() and it()

Have you ever looked at a test file and felt lost in a sea of test() calls? Yeah, me too. That is why Jest gives you describe() and it() to keep things organized. Think of it like putting your clothes in drawers instead of throwing them all on the floor.

describe() creates a group. it() (or test()) defines the actual check inside that group. Together, they make your tests readable and easy to navigate.

Using describe to Group Tests

Let us say you are testing a calculator. You might group all addition tests together, all subtraction tests together, and so on.


describe('Calculator', () => {
  describe('addition', () => {
    it('adds two positive numbers', () => {
      expect(add(2, 3)).toBe(5);
    });

    it('handles negative numbers', () => {
      expect(add(-1, -2)).toBe(-3);
    });
  });

  describe('subtraction', () => {
    it('subtracts two numbers', () => {
      expect(subtract(5, 3)).toBe(2);
    });
  });
});
    

See how nice that reads? When you run your tests, Jest shows you the hierarchy. If the subtraction test fails, you know exactly where to look.

it() vs test()

Quick note. it() and test() do the exact same thing. Some people prefer it() because it reads more like English. "It adds two positive numbers." Others prefer test(). Pick whichever feels natural and stick with it.

Naming Your Tests Well

Good test names tell you what is being tested and what should happen. Instead of "works", write "returns the sum of two numbers". Instead of "handles edge case", write "returns null when input is empty".

When a test fails and you see the name, you should immediately know what broke without looking at the code.

Try it Yourself →

Key Takeaways

  • describe() groups related tests together into logical blocks
  • it() and test() do the same thing, pick one style and be consistent
  • You can nest describe blocks for deeper organization
  • Write descriptive test names that explain the expected behavior