I have a basic Countdown component based on react, and I want to write a suitable unit test for checking number changes. so far I tried two different ways, (the first one, is to tell jest I'm going to wait here so do not worry about time. and the second one, is to mock time changes). but none of them wasn't successful.
First approach:
describe('Test CountdownTimer component', () => {
jest.setTimeout(60000);
test('Shoud show current time 1 second later', async done => {
const { getByText } = render(<CountdownTimer initialTime={10000} />);
await act(async () => {
await new Promise((r) => setTimeout(r, 1000));
})
expect(getByText('00:09')).toBeTruthy();
});
});
Also tired:
describe('Test CountdownTimer component', () => {
jest.setTimeout(60000);
test('Shoud show current time 1 second later', async done => {
const { getByText } = render(<CountdownTimer initialTime={10000} />);
await new Promise((r) => setTimeout(r, 1000));
expect(getByText('00:09')).toBeTruthy();
});
});
Second approach:
describe('Test CountdownTimer component', () => {
beforeEach(() => {
jest.useFakeTimers();
})
test('Shoud show current time 1 second later', async done => {
const { getByText } = render(<CountdownTimer initialTime={10000} />);
act(() => {
jest.advanceTimersByTime(1000);
});
expect(getByText('00:09')).toBeTruthy();
});
});
// error: thrown: "Exceeded timeout of 5000 ms for a test. Use jest.setTimeout(newTimeout) to increase the timeout value, if this is a long-running test."
It's interesting that there isn't any comprehensive tutorial or well-detailed documentation about time-related tests in Jest. 🤔