Mistake: Shared Mutable State
Find the Mistake Medium
Question
What is wrong with this test suite?
Code
let items = [];
test('add item', () => {
items.push('a');
expect(items).toHaveLength(1);
});
test('add another', () => {
items.push('b');
expect(items).toHaveLength(1);
});
Hint
Tests share the items array — order matters.
Explanation
The mistake is shared mutable state. items is declared outside the tests and never reset. The second test adds to the array that already has 'a' from the first test, so items has length 2, not 1. The fix: use beforeEach(() => { items = []; }); to reset state before each test.
Related Resources
Related Lessons
- Setup and Teardown
Test hooks for setup and cleanup.
Look up unfamiliar terms
A beginner-friendly glossary explains jargon in plain English — variables, functions, DOM, Promise, and more.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.
Build real projects
Apply what you learned by building guided projects with starter code and solutions.