Learn Programming, Tech & Coding · Free Online Tools

IT Question Answer
Back to How To Guides
How to Write Good Unit Tests

How to Write Good Unit Tests

How To Guides3,013 viewsBy Admin
testingwritegoodunittests

Advertisement

Writing Effective Unit Tests

Good unit tests are fast, reliable, and clear. Follow these principles to write tests that actually help.

The AAA Pattern

test("applies discount", () => {
  // Arrange
  const cart = { total: 100 };
  // Act
  const result = applyDiscount(cart, 0.1);
  // Assert
  expect(result.total).toBe(90);
});

Principles of Good Tests

  • Fast — run in milliseconds.
  • Isolated — no dependence on other tests.
  • Repeatable — same result every time.
  • Clear names — describe what's tested.

Test Edge Cases

test("handles empty array", () => expect(sum([])).toBe(0));
test("handles negatives", () => expect(sum([-1, -2])).toBe(-3));
test("handles single item", () => expect(sum([5])).toBe(5));

What to Avoid

  • Testing implementation details.
  • Tests that depend on each other.
  • Over-mocking everything.

FAQs

One assertion per test?

Ideally focus each test on one behavior — multiple related asserts are fine. More in our Testing section.

How do I name tests?

Describe behavior: "returns 0 for empty cart".

Advertisement