After this lesson, you will be able to: Write a good unit test using Arrange-Act-Assert, keep tests isolated and deterministic, and use mocking and stubbing only where they belong.
A unit test is the foundation of the pyramid. This lesson is language-agnostic: what makes a unit test good, the structure every test should follow, and the difference between mocks and stubs (asked about constantly in interviews).
A good unit test is fast, isolated, repeatable, and tests one behavior. Fast: milliseconds, so you run the whole suite constantly. Isolated: it does not depend on other tests, shared state, the network, the clock, or the filesystem. Repeatable: it passes or fails the same way every time (no flakiness). Focused: one logical assertion of one behavior, so when it fails you know exactly what broke. A test that needs a paragraph to explain what it checks is testing too much.
Every unit test has the same three-part shape. Keep them visually separated.
// Arrange: set up the inputs and the system under testconst cart = new Cart();cart.add({ id: 'a', price: 10 });cart.add({ id: 'b', price: 5 });// Act: perform the ONE action you are testingconst total = cart.totalWithTax(0.10);// Assert: check the outcomeexpect(total).toBe(16.5);// One behavior per test. If you find yourself asserting five unrelated// things, that is five tests wearing a trench coat. Split them.
A test double replaces a real dependency. A stub returns canned data so the code under test can run (a fake getUser that always returns the same user). A mock additionally verifies HOW it was called (assert that sendEmail was called exactly once with this address). A fake is a lightweight working implementation (an in-memory database). Rule of thumb: stub queries (things that return data), mock commands (things with side effects you need to verify), and prefer a real or fake implementation over a mock whenever it is cheap, because over-mocking produces tests that pass while the real system is broken.
Pick the best choice.
Sign in and purchase access to unlock this lesson.