Benja Vicente
Benja Vicente4mo ago

Recommended way to mock functions of actions, and the "2 dot hack"

Hi! I Couldn't find a recipe or example of how to mock convex actions, for cases where an action depends on external services. Initially, I tried to mock actions directly, but realized that it might be an anti-pattern since the responsibility of an action (from what I understand), is to combine the DB with external services (called via fetch or external function), and we should only mock the external part. So I tried to mock functions with the vitest setup, but the files containing mocks are considered for production deployment (__mocks__/mock-name.js is not a valid path to a Convex module). A "hack" that i found is to trick the bundler include pattern [1], putting 2 dots on every file that is not convex related, for example, tests should end with .spect.ts or .test.ts, and utils with .utils.ts, and so on. With that, I was able to test with the following structure: [1]: https://github.com/get-convex/convex-js/blob/a2a7eb76e9a851c360f926508d2a7208929733d4/src/bundler/index.ts#L359
convex
├── __mocks__
│   └── todo.utils.ts
├── __tests__
│   ├── setup.tests.ts
│   └── shared.tests.ts
├── _generated ...
├── schema.ts
├── todo.ts
├── todo.utils.ts
└── todos.spec.ts
convex
├── __mocks__
│   └── todo.utils.ts
├── __tests__
│   ├── setup.tests.ts
│   └── shared.tests.ts
├── _generated ...
├── schema.ts
├── todo.ts
├── todo.utils.ts
└── todos.spec.ts
Gist of the code: https://gist.github.com/benjavicente/d083d2cd1287f81ca4d9220438cdd7ab Is this "hack" ok, or the 2 dot trick to ignore files might break in the future? Or we should consider other ways to organize code for testing?
1 Reply
Convex Bot
Convex Bot4mo 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!

Did you find this page helpful?