Benja Vicente
Benja Vicente
CCConvex Community
Created by Benja Vicente on 10/4/2024 in #support-community
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?
2 replies