-
Right now I am trying to test authorisation. My current Jest test: import { UserRole } from "@prisma/client";
import { trpcRequest, suppressErrorConsole } from "~/test/helpers";
describe("trpc.findManyPost", () => {
it("does not allow USER role", () => {
const { restoreErrorConsole } = suppressErrorConsole();
expect(() => {
trpcRequest().post.findManyPost({});
}).toThrow("Not Authorised");
restoreErrorConsole();
});
it("does allow a SUPERUSER to read", () => {
expect(() =>
trpcRequest({
id: "123",
role: UserRole.SUPERUSER,
}).post.findManyPost({})
).not.toThrow();
});
}); Where /**
* @see https://github.com/echobind/bisonapp/blob/c6c7f3604c99d5f27bf351f9a8c6f3e980e2af89/packages/create-bison-app/template/tests/helpers/trpcRequest.ts
*/
import { User, UserRole } from "@prisma/client";
import { appRouter } from "~/server/routers";
import prisma from "~/utils/prisma";
import { faker } from "@faker-js/faker";
type UserType = Pick<User, "id" | "role">;
function createTestContext(user: UserType) {
return {
prisma,
user,
};
}
/** A convenience method to call tRPC queries */
export const trpcRequest = (
user: UserType = {
id: faker.string.uuid(),
role: UserRole.USER,
}
) => {
return appRouter.createCaller(createTestContext(user));
}; In my const isSuperUser = rule<Context>()(async (ctx) => {
return ctx.user?.role === UserRole.SUPERUSER;
}); Then, down in my query rule I have Right now, the second test with the authorised user works as expected, however my first test fails and Jest exits the process without throwing the error. I thought maybe Does anyone have a configuration that works? Or have I misconfigured something from the tRPC side? |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
Ahhh I actually figured this out! Needed the it("does not allow USER role", () => {
const t = async () => {
await trpcRequest().post.findManyPost({});
};
expect(t).rejects.toThrow();
}); Woo! |
Beta Was this translation helpful? Give feedback.
Ahhh I actually figured this out! Needed the
rejects
for the promise. For example:Woo!