Mistake: Hardcoded Time in Test
Find the Mistake Medium
Question
What is wrong with this time-based test?
Code
test('greeting', () => {
const hour = new Date().getHours();
const greeting = getGreeting();
expect(greeting).toBe('Good morning'); // assumes it's morning
});
Hint
The test will fail at different times of day.
Explanation
The mistake is relying on the real current time. The test assumes it's morning, but it will fail when run in the afternoon or evening. The fix: mock the Date object to control the time: jest.useFakeTimers().setSystemTime(new Date('2024-01-01T08:00:00')); or pass the hour as a parameter to getGreeting for testability.
Related Resources
Related Lessons
- Test Best Practices
Writing maintainable tests.
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.