I have a function that allows users to register. After successful registration, the user is redirected to the home page (after 5 seconds). Before being redirected, the user receives a toast notification to see whether the registration was successful or not.
The problem that I have: I don't know how to remove the setTimeout function in the test, because I want to check whether the message is displayed correctly and the redirection is working. I have already tried fakeTimers from vi, but when I use it, I get a timeout error for every subsequent test + the current test.
Code:
const onSubmit = async (formData) => {
try {
await registerUserAPI(formData, setError);
} catch (error) {
toast.error(data.detail || "Registration failed: An unknown page error occurred. You will be redirected shortly...");
setTimeout(() => {
window.location.href = "/";
}, 5000);
};
};
Test function:
it("Registration was successful and redirects after 5 seconds", async () => {
vi.useFakeTimers();
delete window.location;
window.location = { href: "" };
fetch.mockResolvedValueOnce({
ok: true,
status: 201,
json: async () => ({})
});
render(<Register />);
await userEvent.type(usernameInput, testUsername);
await userEvent.type(emailInput, testEmail);
await userEvent.type(passwordInput, testPassword);
await userEvent.click(submitButton);
const successMessage = await screen.findByText(
"Registration successful! You will be redirected to the homepage shortly."
);
expect(successMessage).toBeInTheDocument();
await act(async () => {
vi.advanceTimersByTime(5000);
});
expect(window.location.href).toBe("/");
vi.useRealTimers();
});
Error:
FAIL src/__test__/pages/auth/Register.test.jsx > Register > Registration was successful and redirects after 5 seconds
Error: Test timed out in 5000ms.
If this is a long-running test, pass a timeout value as the last argument or configure it globally with "testTimeout".
❯ src/__test__/pages/auth/Register.test.jsx:81:5
79|
80|
81| it("Registration was successful and redirects after 5 seconds", async () => {
| ^
82| vi.useFakeTimers();
83|