Jest · Unit tests that survive refactors
How do describe blocks and hooks work together?
Short answer
describe groups tests and scopes hooks to that group. beforeEach and afterEach run around every test in the block, while beforeAll and afterAll run once for the block.
Hooks are registered inside the currently executing describe. That means a hook declared in an outer block applies to every nested test, and a hook in an inner block applies only there. Jest records the nesting and runs hooks from the outside in on setup, then inside out on teardown.
describe("cart", () => {
let cart: Cart;
beforeEach(() => {
cart = createCart();
});
afterEach(() => {
cart.clear();
});
describe("with an item", () => {
beforeEach(() => {
cart.add({ sku: "A1", price: 20 });
});
test("has a subtotal", () => {
expect(cart.subtotal()).toBe(20);
});
});
});Hook order for a nested test
- Outer beforeEach runs first
- Inner beforeEach runs next
- The test body runs
- Inner afterEach runs first
- Outer afterEach runs last
Use hooks for setup that every case in the block needs. If only one test needs a value, build it inside that test. Hidden setup is a common source of confusion because a reader sees a bare test body and cannot tell what state already exists.
describe block is not a lifecycle scope for module state. Modules are loaded per test file, not per describe block. Use jest.resetModules() inside a hook if you truly need a fresh module instance.Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1In what order do nested beforeEach and afterEach hooks run?
- 2When is beforeAll appropriate?
- 3Do describe blocks reset module state?
- 4Why can hidden beforeEach setup make a test hard to read?
Say it in the interview
describe groups tests and scopes hooks. Outer beforeEach hooks run before inner ones, then the test runs, then inner afterEach hooks run before outer ones. I put setup in beforeEach only when every test in that block needs it, and keep it visible near the tests. beforeAll is for expensive setup that is safe to share, not for mutable state.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Jest mock interview and get scored feedback on depth, clarity and confidence.