Skip to content

Commit

Permalink
reproduce error in test
Browse files Browse the repository at this point in the history
  • Loading branch information
edmundhung committed Feb 21, 2025
1 parent 9271f4a commit 1baf04c
Show file tree
Hide file tree
Showing 4 changed files with 81 additions and 22 deletions.
5 changes: 5 additions & 0 deletions .changeset/quick-shoes-jump.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@cloudflare/vitest-pool-workers": patch
---

fix mock modules not re-evaluated in watch mode
Original file line number Diff line number Diff line change
Expand Up @@ -230,28 +230,10 @@ export default class WorkersTestRunner extends VitestTestRunner {
await scheduler.wait(100);
}

// Reset the module graphs so module mock will be re-evalated on watch mode
// See https://github.com/cloudflare/workers-sdk/issues/6844
// This is basically `vi.resetModules()`
// From https://github.com/vitest-dev/vitest/blob/9584be337f00e22475895360cb5cfa5dc0775e79/packages/vitest/src/runtime/utils.ts#L50-L68
// const skipPaths = [
// // Vitest
// /\/vitest\/dist\//,
// /\/vite-node\/dist\//,
// // yarn's .store folder
// /vitest-virtual-\w+\/dist/,
// // cnpm
// /@vitest\/dist/,
// // don't clear mocks
// /^mock:/,
// ];
// this.state.moduleCache.forEach((mod, path) => {
// if (skipPaths.some((re) => re.test(path))) {
// return;
// }
// this.state.moduleCache.invalidateModule(mod);
// });
vi.resetModules();
// Unlike the official threads and forks pool, we do not recycle the miniflare instances to maintains the module cache.
// However, this creates a side effect where the module mock will not be re-evaluated on watch mode.
// This fixes https://github.com/cloudflare/workers-sdk/issues/6844 by resetting the module graph.
// vi.resetModules();

// Ensure all `ctx.waitUntil()` calls complete before disposing the runtime
// (if using `vitest run`) and aborting all objects. `ctx.waitUntil()`s may
Expand Down
4 changes: 4 additions & 0 deletions packages/vitest-pool-workers/test/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ export interface Process {
readonly stdout: string;
readonly stderr: string;
readonly exitCode: Promise<number>;
readonly write: (chunk: unknown) => void;
}

function wrap(proc: childProcess.ChildProcess): Process {
Expand Down Expand Up @@ -75,6 +76,9 @@ function wrap(proc: childProcess.ChildProcess): Process {
get exitCode() {
return closePromise.then(([exitCode]) => exitCode ?? -1);
},
write(chunk) {
proc.stdin?.write(chunk);
},
};
}

Expand Down
68 changes: 68 additions & 0 deletions packages/vitest-pool-workers/test/watch.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,3 +106,71 @@ test("automatically re-runs integration tests", async ({
expect(result.stdout).toMatch("Tests 1 passed");
});
});

test("automatically reset module graph", async ({
expect,
seed,
vitestDev,
}) => {
await seed({
"vitest.config.mts": dedent`
import { defineWorkersConfig } from "@cloudflare/vitest-pool-workers/config";
export default defineWorkersConfig({
test: {
poolOptions: {
workers: {
main: "./index.ts",
singleWorker: true,
},
},
}
});
`,
"index.ts": dedent`
import { getAnswer } from "./answer";
export default {
async fetch(request, env, ctx) {
const answer = getAnswer();
return new Response(answer);
}
}
`,
"answer.ts": dedent`
export function getAnswer() {
return "wrong";
}
`,
"index.test.ts": dedent`
import { env, createExecutionContext, waitOnExecutionContext } from "cloudflare:test";
import { it, expect, vi } from "vitest";
import worker from "./index";
import { getAnswer } from './answer';
vi.mock('./answer.ts');
it("mocks module properly in watch mode", async () => {
vi.mocked(getAnswer).mockReturnValue("Correct");
const request = new Request("https://example.com");
const ctx = createExecutionContext();
const response = await worker.fetch(request, env, ctx);
await waitOnExecutionContext(ctx);
expect(await response.text()).toBe("correct");
});
`,
});
const result = vitestDev();

await waitFor(() => {
expect(result.stdout).toMatch("Tests 1 passed");

Check failure on line 166 in packages/vitest-pool-workers/test/watch.test.ts

View workflow job for this annotation

GitHub Actions / Tests (macOS)

test/watch.test.ts > automatically reset module graph

AssertionError: expected '\n DEV v3.0.6 /private/var/folders/2…' to match 'Tests 1 passed' - Expected + Received - Tests 1 passed + + DEV v3.0.6 /private/var/folders/2s/h6hvv9ps03xgz_krkkstvq_r0000gn/T/vitest-pool-workers temp-gbE9cM/test-IN4466 + + + Test Files no tests + Tests no tests + Errors 1 error + Start at 11:53:38 + Duration 211ms (transform 0ms, setup 0ms, collect 0ms, tests 0ms, environment 0ms, prepare 0ms) + + FAIL Tests failed. Watching for file changes... + press h to show help, press q to quit + ❯ test/watch.test.ts:166:25

Check failure on line 166 in packages/vitest-pool-workers/test/watch.test.ts

View workflow job for this annotation

GitHub Actions / Tests (Windows)

test/watch.test.ts > automatically reset module graph

AssertionError: expected '\n DEV v3.0.6 C:/Users/runneradmin/A…' to match 'Tests 1 passed' - Expected + Received - Tests 1 passed + + DEV v3.0.6 C:/Users/runneradmin/AppData/Local/Temp/vitest-pool-workers temp-ClYQ0O/test-Zr1eyx + + + Test Files no tests + Tests no tests + Errors 1 error + Start at 11:53:18 + Duration 429ms (transform 0ms, setup 0ms, collect 0ms, tests 0ms, environment 0ms, prepare 0ms) + + FAIL Tests failed. Watching for file changes... + press h to show help, press q to quit + ❯ test/watch.test.ts:166:25

Check failure on line 166 in packages/vitest-pool-workers/test/watch.test.ts

View workflow job for this annotation

GitHub Actions / Tests (Linux)

test/watch.test.ts > automatically reset module graph

AssertionError: expected '\n DEV v3.0.6 /tmp/vitest-pool-worke…' to match 'Tests 1 passed' - Expected + Received - Tests 1 passed + + DEV v3.0.6 /tmp/vitest-pool-workers temp-AHmkhS/test-v1840e + + + Test Files no tests + Tests no tests + Errors 1 error + Start at 11:53:08 + Duration 320ms (transform 0ms, setup 0ms, collect 0ms, tests 0ms, environment 0ms, prepare 0ms) + + FAIL Tests failed. Watching for file changes... + press h to show help, press q to quit + ❯ test/watch.test.ts:166:25
});

const enterKey = "\x0d";
result.write(enterKey);

// result.stdout
await waitFor(() => {
expect(result.stdout).toMatch("Tests 1 passed");
});
});

0 comments on commit 1baf04c

Please sign in to comment.