Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add test coverage #9

Open
wants to merge 10 commits into
base: main
Choose a base branch
from
20 changes: 20 additions & 0 deletions .github/workflows/node.js.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
name: Run tests
on:
push:
branches: ["main"]
pull_request:
branches: ["main"]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Use Node.js
uses: actions/setup-node@v4
with:
node-version: "18.x"
cache: "npm"
- run: npm i
- run: npm ci
- run: cd example && npm i && cd ..
- run: npm test
2 changes: 0 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,6 @@ dist-ssr
explorations
node_modules
.eslintcache
# components are libraries!
package-lock.json

# this is a package-json-redirect stub dir, see https://github.com/andrewbranch/example-subpath-exports-ts-compat?tab=readme-ov-file
frontend/package.json
Expand Down
161 changes: 161 additions & 0 deletions example/convex/client.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,161 @@
/// <reference types="vite/client" />

import { convexTest } from "convex-test";
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
import { Migrations } from "@convex-dev/migrations";
import { DataModel } from "./_generated/dataModel";
import schema from "./schema";
import componentSchema from "../../src/component/schema";
import migrationsSchema from "../node_modules/@convex-dev/migrations/src/component/schema";
import { api, components, internal } from "./_generated/api";

const migrationsModules = import.meta.glob(
"../node_modules/@convex-dev/migrations/src/component/**/*.ts"
);

const modules = import.meta.glob("./**/*.ts");
const componentModules = import.meta.glob("../../src/component/**/*.ts");

describe("migrations client", () => {
async function setupTest() {
const t = convexTest(schema, modules);
t.registerComponent("migrations", migrationsSchema, migrationsModules);
await t.mutation(internal.example.seed, { count: 10 });
return t;
}

let testEnv: {
t: ReturnType<typeof convexTest>;
migrations: Migrations<DataModel>;
testMigration: ReturnType<typeof Migrations.prototype.define>;
};

beforeEach(async () => {
vi.useFakeTimers();
const t = await setupTest();
const migrations = new Migrations<DataModel>(components.migrations);
const testMigration = migrations.define({
table: "myTable",
migrateOne: async (ctx: { db: any }, doc: { optionalField?: string }) => ({ optionalField: "default" })
});
Comment on lines +37 to +40
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

you'll need to define the migration as a public export of this file and provide a reference to it like here with testApi.foo: https://github.com/get-convex/convex-helpers/blob/main/packages/convex-helpers/server/customFunctions.test.ts#L360-L381

testEnv = { t, migrations, testMigration };
});

afterEach(async () => {
await testEnv.t.finishAllScheduledFunctions(vi.runAllTimers);
vi.useRealTimers();
});

test("run basic migration", async () => {
const { t, migrations, testMigration } = testEnv;

await migrations.runOne(t, testMigration);

Check failure on line 52 in example/convex/client.test.ts

View workflow job for this annotation

GitHub Actions / build

example/convex/client.test.ts > migrations client > run basic migration

Error: (ctx, args) => { globalThis.console.warn( `Convex functions should not directly call other Convex functions. Consider calling a helper function instead. e.g. \`export const foo = ${funcType}(...); await foo(ctx);\` is not supported. See https://docs.convex.dev/production/best-practices/#use-helper-functions-to-write-shared-code` ); return handler(ctx, args); } is not a functionReference ❯ getFunctionAddress node_modules/convex/src/server/components/paths.ts:43:13 ❯ getFunctionName node_modules/convex/src/server/api.ts:81:19 ❯ Migrations.runOne src/client/index.ts:458:28 ❯ example/convex/client.test.ts:52:22

const docs = await t.query("myTable").collect();
for (const doc of docs) {
expect(doc.optionalField).toBe("default");
}
});

test("run validation migration", async () => {
const { t, migrations } = testEnv;

const validateMigration = migrations.define({
table: "myTable",
customRange: (query) =>
query.withIndex("by_requiredField", (q) => q.eq("requiredField", "")),
migrateOne: async (ctx, doc: { requiredField?: string }) => {
return { requiredField: "<unknown>" };
},
});

await migrations.runOne(t, validateMigration);

Check failure on line 72 in example/convex/client.test.ts

View workflow job for this annotation

GitHub Actions / build

example/convex/client.test.ts > migrations client > run validation migration

Error: (ctx, args) => { globalThis.console.warn( `Convex functions should not directly call other Convex functions. Consider calling a helper function instead. e.g. \`export const foo = ${funcType}(...); await foo(ctx);\` is not supported. See https://docs.convex.dev/production/best-practices/#use-helper-functions-to-write-shared-code` ); return handler(ctx, args); } is not a functionReference ❯ getFunctionAddress node_modules/convex/src/server/components/paths.ts:43:13 ❯ getFunctionName node_modules/convex/src/server/api.ts:81:19 ❯ Migrations.runOne src/client/index.ts:458:28 ❯ example/convex/client.test.ts:72:22

const docs = await t.query("myTable")
.withIndex("by_requiredField", (q) => q.eq("requiredField", ""))
.collect();
expect(docs).toHaveLength(0);
});

test("run type conversion migration", async () => {
const { t, migrations } = testEnv;

const convertMigration = migrations.define({
table: "myTable",
migrateOne: async (ctx: { db: any }, doc: { _id: any; unionField: string | number }) => {
if (typeof doc.unionField === "number") {
await ctx.db.patch(doc._id, { unionField: doc.unionField.toString() });
}
},
});

await migrations.runOne(t, convertMigration);

Check failure on line 92 in example/convex/client.test.ts

View workflow job for this annotation

GitHub Actions / build

example/convex/client.test.ts > migrations client > run type conversion migration

Error: (ctx, args) => { globalThis.console.warn( `Convex functions should not directly call other Convex functions. Consider calling a helper function instead. e.g. \`export const foo = ${funcType}(...); await foo(ctx);\` is not supported. See https://docs.convex.dev/production/best-practices/#use-helper-functions-to-write-shared-code` ); return handler(ctx, args); } is not a functionReference ❯ getFunctionAddress node_modules/convex/src/server/components/paths.ts:43:13 ❯ getFunctionName node_modules/convex/src/server/api.ts:81:19 ❯ Migrations.runOne src/client/index.ts:458:28 ❯ example/convex/client.test.ts:92:22

const docs = await t.query("myTable").collect();
for (const doc of docs) {
expect(typeof doc.unionField).toBe("string");
}
});

test("run batch migration with parallelize", async () => {
const { t, migrations } = testEnv;

const batchMigration = migrations.define({
table: "myTable",
batchSize: 2,
parallelize: true,
migrateOne: async (ctx, doc: { processed?: boolean }) => {
return { processed: true };
},
});

await migrations.runOne(t, batchMigration);

Check failure on line 112 in example/convex/client.test.ts

View workflow job for this annotation

GitHub Actions / build

example/convex/client.test.ts > migrations client > run batch migration with parallelize

Error: (ctx, args) => { globalThis.console.warn( `Convex functions should not directly call other Convex functions. Consider calling a helper function instead. e.g. \`export const foo = ${funcType}(...); await foo(ctx);\` is not supported. See https://docs.convex.dev/production/best-practices/#use-helper-functions-to-write-shared-code` ); return handler(ctx, args); } is not a functionReference ❯ getFunctionAddress node_modules/convex/src/server/components/paths.ts:43:13 ❯ getFunctionName node_modules/convex/src/server/api.ts:81:19 ❯ Migrations.runOne src/client/index.ts:458:28 ❯ example/convex/client.test.ts:112:22

const docs = await t.query("myTable").collect();
for (const doc of docs) {
expect(doc.processed).toBe(true);
}
});

test("handle failing migration", async () => {
const { t, migrations } = testEnv;

const failingMigration = migrations.define({
table: "myTable",
migrateOne: async (_ctx, _doc) => {
throw new Error("Migration failed");
},
});

await expect(migrations.runOne(t, failingMigration)).rejects.toThrow("Migration failed");
});

test("track migration state", async () => {
const { t, migrations } = testEnv;

const stateMigration = migrations.define({
table: "myTable",
migrateOne: async (ctx, doc: { state?: string }) => {
return { state: "migrated" };
},
});

const migration = migrations.runOne(t, stateMigration);

Check failure on line 143 in example/convex/client.test.ts

View workflow job for this annotation

GitHub Actions / build

Unhandled error

Error: (ctx, args) => { globalThis.console.warn( `Convex functions should not directly call other Convex functions. Consider calling a helper function instead. e.g. \`export const foo = ${funcType}(...); await foo(ctx);\` is not supported. See https://docs.convex.dev/production/best-practices/#use-helper-functions-to-write-shared-code` ); return handler(ctx, args); } is not a functionReference ❯ getFunctionAddress node_modules/convex/src/server/components/paths.ts:43:13 ❯ getFunctionName node_modules/convex/src/server/api.ts:81:19 ❯ Migrations.runOne src/client/index.ts:458:28 ❯ example/convex/client.test.ts:143:34 ❯ node_modules/@vitest/runner/dist/index.js:174:14 ❯ node_modules/@vitest/runner/dist/index.js:561:28 ❯ node_modules/@vitest/runner/dist/index.js:61:24 ❯ runWithTimeout node_modules/@vitest/runner/dist/index.js:41:12 ❯ runTest node_modules/@vitest/runner/dist/index.js:1140:17 This error originated in "example/convex/client.test.ts" test file. It doesn't mean the error was thrown inside the file itself, but while it was running. The latest test that might've caused the error is "example/convex/client.test.ts". It might mean one of the following: - The error was thrown, while Vitest was running this test. - If the error occurred after the test had been completed, this was the last documented test before it was thrown.

// Check initial state
let status = await t.query(api.lib.getStatus, { names: ["stateMigration"] });

Check failure on line 146 in example/convex/client.test.ts

View workflow job for this annotation

GitHub Actions / build

example/convex/client.test.ts > migrations client > track migration state

Error: Could not find module for: "lib" ❯ example/node_modules/convex-test/dist/index.js:989:19 ❯ getFunctionFromPath example/node_modules/convex-test/dist/index.js:1364:76 ❯ Object.queryFromPath example/node_modules/convex-test/dist/index.js:1153:32 ❯ Object.query example/node_modules/convex-test/dist/index.js:1202:41 ❯ example/convex/client.test.ts:146:18
expect(status[0].state).toBe("inProgress");

await migration;

// Check final state
status = await t.query(api.lib.getStatus, { names: ["stateMigration"] });
expect(status[0]).toMatchObject({
isDone: true,
state: "success",
processed: expect.any(Number),
latestStart: expect.any(Number),
latestEnd: expect.any(Number)
});
});
});
Loading