Eva
Eva2w ago

Testing `withIdentity` in `convex-test`

Hello! I've created a custom mutation for userMutation and a custom query for userQuery which use getAuthUserId to pass along the current userId and verify that a user is authenticated. I then use these custom mutations and queries whenever I want one of my Convex functions to run with authentication for the current user. I want to write tests for these queries and mutations, and I understand I can use t.withIdentity to mock a user account. How can I get the mock id from the withIdentity user? When I try accessing it, I get a typescript error that the mocked user's id doesn't exist on Id<"users">.
4 Replies
Convex Bot
Convex Bot2w ago
Thanks for posting in <#1088161997662724167>. Reminder: If you have a Convex Pro account, use the Convex Dashboard to file support tickets. - Provide context: What are you trying to achieve, what is the end-user interaction, what are you seeing? (full error message, command output, etc.) - Use search.convex.dev to search Docs, Stack, and Discord all at once. - Additionally, you can post your questions in the Convex Community's <#1228095053885476985> channel to receive a response from AI. - Avoid tagging staff unless specifically instructed. Thank you!
Eva
EvaOP2w ago
Put another way — is there a way to mock the ctx of a Convex function during testing?
terms
terms2w ago
Create a user document with whatever values are important to your functions. Plug the returned id into t.withIdentity({ subject: ``${id}|-`` }) Omit the extra backticks, couldn't figure markdown sorry
Eva
EvaOP2w ago
What is the subject field? Ah, that worked! Thank you!
const userId = await t.run(async (ctx) => {
return await ctx.db.insert("users", {
email: "test@example.com",
role: "user",
});
});

const asUser = t.withIdentity({ subject: userId });

await asUser.mutation( ...an auth-required mutation )
const userId = await t.run(async (ctx) => {
return await ctx.db.insert("users", {
email: "test@example.com",
role: "user",
});
});

const asUser = t.withIdentity({ subject: userId });

await asUser.mutation( ...an auth-required mutation )