Next.js Discord

Discord Forum

How to test redirect in server actions

Unanswered
Cape lion posted this in #help-forum
Open in Discord
Avatar
Cape lionOP
I have the following test

export class TestRedirect extends Error {
  readonly url: string;
  constructor(url: string) {
    super();
    this.url = url;
  }
}


vi.mock("next/navigation", () => ({
  redirect: vi.fn().mockImplementation((path) => {
    throw new TestRedirect(path);
  }),
}));

vi.mock("@/auth/session", () => ({
  requireAdmin: vi.fn(),
}));

describe("CreateEventPage", () => {
  dbTest("submits successfully when the name is provided", async () => {
    render(
      <ErrorBoundary fallback={null} onError={() => {}}>
        <CreateEventPage />
      </ErrorBoundary>
    );

    const input = screen.getByPlaceholderText("Jane and John's Wedding");
    const submitButton = screen.getByRole("button", { name: /create/i });

    // Enter a valid event name and submit
    fireEvent.change(input, { target: { value: "Wedding Celebration" } });
    await fireEvent.click(submitButton);

    // Verify the event was created in the database
    const [event] = await events.findAll();
    expect(event).toMatchObject({
      name: "Wedding Celebration",
    });

    // Check that the user was redirected to the event page
    expect(redirect).toHaveBeenCalledWith(`/events/${event.id}`);

    // Check that the user is an admin
    expect(requireAdmin).toHaveBeenCalled();
  });


This passes but the error is still shown in the console. Is there a way to silence the redirect error or perhaps a better way to test redirects?

0 Replies