Jest · Unit tests that survive refactors
How should you name tests and describe blocks?
Short answer
Name a test as a sentence about behaviour: subject, scenario and expected outcome. Good names document the contract and make a failure readable without opening the implementation.
Test names are read far more often than they are written: in CI output, in a pull request, and by the next person debugging a failure. A name like works says nothing. A name like returns an empty list when the account has no orders states the contract.
describe("applyDiscount", () => {
test("returns zero for an empty cart", () => {
expect(applyDiscount([], 0.2)).toBe(0);
});
test("caps the discount at the cart subtotal", () => {
expect(applyDiscount([{ price: 10 }], 5)).toBe(0);
});
});What a good name contains
- The behaviour or subject, not the function name repeated
- The condition or input that makes the case distinct
- The expected outcome in plain language
- No vague words such as works, handles or should be correct
- No reference to internal helpers the reader cannot see
Keep names stable when the implementation changes. A test named after a hook or a state variable will become wrong after a refactor, even if the behaviour is unchanged. Name the externally observable result instead.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What is wrong with a test named should work?
- 2Should a test name mention the function under test?
- 3How do you name tests for error cases?
- 4Why can implementation-based test names become stale?
Say it in the interview
I name tests as a behaviour sentence: the scenario and the expected outcome. That way a CI failure already tells me what broke. I avoid vague words like works and avoid naming internal state or hooks, because those names go stale after a refactor. The describe block names the unit, and the individual test names the case.
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.