#Testing thrown responses in Vitest

1 messages · Page 1 of 1 (latest)

azure sierra
#

Hi all!

Recently upgraded Remix and a lot of my tests broke. As an example:

I have this function that will throw a response which i call at the top of an action:

export const validateAdminActionUser = async ({
  request,
}: {
  request: Request;
  model: PrismaModelName;
}) => {
  const sessionUser = await getUserSession(request);
  if (!sessionUser) {
    throw new Response("Unauthorized", { status: 401 });
  }
}

I used to be able to write a test like so:

import { action } from '~/whatever-route'
...

it("should throw a response", async () => {
          const request = new Request(
            `http://localhost:3000/my-route`,
            {
              method: "POST",
              body,
            }
          );

          const result = action({
            request,
            params: { id: order.id },
            context: {},
          });

          await expect(result).rejects.toThrow(Response);
          await expect(result).rejects.toEqual(
            new Response("Unauthorized to write", { status: 401 })
          );
        });

But this no longer works, because it no longer directly returns new Response("Unauthorized to write", { status: 401 }) - it's a readable stream.

Any suggestions on a better way to test the responses on reject?

prisma mesa
#

You should be checking props / return values from Response, not response directly:

const result = action(...);
expect(result).rejects.toThrow(async response => {
  expect(response.status).toBe(401);
  expect(await response.text()).toBe("Unauthorized to write");
});