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

feat(react-server): vitest integration #49

Merged
merged 5 commits into from
Apr 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ jobs:
- run: pnpm -C examples/react-server test-e2e
- run: pnpm -C examples/react-server build
- run: pnpm -C examples/react-server test-e2e-preview
- run: pnpm -C examples/react-server test
- run: pnpm -C examples/vue-ssr test-e2e
- run: pnpm -C examples/vue-ssr build
- run: pnpm -C examples/vue-ssr test-e2e-preview
Expand Down
6 changes: 5 additions & 1 deletion examples/react-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
"dev": "vite",
"build": "vite build --all",
"preview": "vite preview",
"test": "vitest",
"test-e2e": "playwright test",
"test-e2e-preview": "E2E_PREVIEW=1 playwright test",
"cf-build": "SERVER_ENTRY=/src/adapters/cloudflare-workers.ts pnpm build && bash misc/cloudflare-workers/build.sh",
Expand All @@ -20,7 +21,10 @@
"devDependencies": {
"@hiogawa/vite-plugin-ssr-middleware-alpha": "workspace:*",
"@types/react": "18.2.72",
"@types/react-dom": "18.2.22"
"@types/react-dom": "18.2.22",
"@types/react-test-renderer": "^18.0.7",
"happy-dom": "^14.7.1",
"react-test-renderer": "19.0.0-canary-4c12339ce-20240408"
},
"volta": {
"extends": "../../package.json"
Expand Down
99 changes: 99 additions & 0 deletions examples/react-server/src/__snapshots__/basic.test.tsx.snap
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
// Vitest Snapshot v1, https://vitest.dev/guide/snapshot.html

exports[`basic 1`] = `
<body>
<div>
<h4>
Hello Server Component
</h4>
<div
data-testid="server-action"
>
<h4>
Hello Server Action
</h4>
<form
action="javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')"
>
<div>
Count:
0
</div>
<button
name="value"
value="-1"
>
-1
</button>
<button
name="value"
value="1"
>
+1
</button>
</form>
<form
action="javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')"
>
<h4>
Hello useActionState
</h4>
<div
style="display: flex; align-items: center; gap: 0.3rem;"
>
<div>
1 + 1 =
</div>
<input
name="answer"
placeholder="Answer?"
required=""
/>
<div
data-testid="action-state"
/>
</div>
</form>
</div>
<div
data-testid="client-component"
>
<h4>
Hello Client Component
</h4>
<div
data-hydrated="true"
>
hydrated:
true
</div>
<div>
Count:
0
</div>
<button>
-1
</button>
<button>
+1
</button>
</div>
</div>
</body>
`;

exports[`test async 1`] = `
<body>
<div>
<div>
hello
</div>
<pre>
{
"name": "@hiogawa/vite-environment-examples-react-server",
"private": true,
"type": "module"
</pre>
</div>
</body>
`;
59 changes: 59 additions & 0 deletions examples/react-server/src/basic.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import { test, expect, beforeEach, vi } from "vitest";
import { initializeWebpackBrowser } from "./features/use-client/browser";
import React from "react";
import { createManualPromise } from "@hiogawa/utils";
import reactDomClient from "react-dom/client";
import { Window } from "happy-dom";

// happy-dom
beforeEach(() => {
const window = new Window({ url: "https://localhost:8080" });
Object.assign(globalThis, {
window,
document: window.document,
});
return () => {
window.close();
};
});

async function testRender(page: string) {
// react client browser
initializeWebpackBrowser();
const { default: reactServerDomClient } = await import(
"react-server-dom-webpack/client.browser"
);

// fetch rsc stream via virtual module
const testStream = await import("virtual:test-react-server-stream" + page);
const testNode =
reactServerDomClient.createFromReadableStream<React.ReactNode>(
testStream.default,
);

// render
const mounted = createManualPromise<void>();

function Root() {
React.useEffect(() => {
mounted.resolve();
}, []);
return React.use(testNode);
}

reactDomClient.createRoot(document.body).render(<Root />);
await mounted;
}

test("basic", async () => {
await testRender("/src/routes/page");
await vi.waitUntil(() =>
document.body.querySelector(`[data-hydrated="true"]`),
);
expect(document.body).toMatchSnapshot();
});

test("test async", async () => {
await testRender("/src/routes/test/page");
expect(document.body).toMatchSnapshot();
});
7 changes: 7 additions & 0 deletions examples/react-server/src/entry-react-server.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,10 @@ export async function handler({

return { stream, actionResult };
}

export async function testRender(Comp: React.ComponentType) {
return reactServerDomServer.renderToReadableStream(
<Comp />,
createBundlerConfig(),
);
}
49 changes: 49 additions & 0 deletions examples/react-server/src/features/test/plugin.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import type { Plugin } from "vite";
import { $__global } from "../../global";

export function vitePluginTestReactServerStream(): Plugin {
const prefix = "virtual:test-react-server-stream/";

return {
name: vitePluginTestReactServerStream.name,
resolveId(source, _importer, _options) {
if (source.startsWith(prefix)) {
return "\0" + source;
}
return;
},
async load(id, _options) {
if (id.startsWith("\0" + prefix)) {
const page = id.slice(prefix.length);
this.addWatchFile(page);
const stream = await testRender(page);
let stringified = "";
await stream.pipeThrough(new TextDecoderStream()).pipeTo(
new WritableStream({
write(chunk) {
stringified += chunk;
},
}),
);
const code = `
export default new ReadableStream({
start(controller) {
controller.enqueue(${JSON.stringify(stringified)});
controller.close();
}
}).pipeThrough(new TextEncoderStream());
`;
return code;
}
return;
},
};
}

async function testRender(page: string) {
const runner = $__global.reactServerRunner;
const entryMod = await runner.import("/src/entry-react-server");
const pageMod = await runner.import(page);
const stream = entryMod.testRender(pageMod.default);
return stream;
}
4 changes: 4 additions & 0 deletions examples/react-server/src/features/test/virtual.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
declare module "virtual:test-react-server-stream/*" {
const stream: ReadableStream<Uint8Array>;
export default stream;
}
2 changes: 1 addition & 1 deletion examples/react-server/src/routes/_client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export function ClientComponent() {
return (
<div data-testid="client-component">
<h4>Hello Client Component</h4>
<div>hydrated: {String(hydrated)}</div>
<div data-hydrated={hydrated}>hydrated: {String(hydrated)}</div>
<div>Count: {count}</div>
<button onClick={() => setCount((v) => v - 1)}>-1</button>
<button onClick={() => setCount((v) => v + 1)}>+1</button>
Expand Down
2 changes: 1 addition & 1 deletion examples/react-server/src/routes/page.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { changeCounter, getCounter } from "./_action";
import { ClientComponent, UseActionStateDemo } from "./_client";

export default function Page() {
export default async function Page() {
return (
<div>
<h4>Hello Server Component</h4>
Expand Down
11 changes: 11 additions & 0 deletions examples/react-server/src/routes/test/page.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import fs from "node:fs";

export default async function Page() {
const pkg = await fs.promises.readFile("package.json", "utf-8");
return (
<div>
<div>hello</div>
<pre>{pkg.slice(0, 100)}</pre>
</div>
);
}
8 changes: 7 additions & 1 deletion examples/react-server/vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,22 @@ import {
} from "./src/features/utils/plugin";
import fs from "node:fs";
import { resolve } from "node:path";
import { vitePluginTestReactServerStream } from "./src/features/test/plugin";

const debug = createDebug("app");

export default defineConfig((_env) => ({
clearScreen: false,
appType: "custom",
plugins: [
react(),
!process.env["VITEST"] && react(),
vitePluginReactServer(),
vitePluginLogger(),
vitePluginSsrMiddleware({
entry: process.env["SERVER_ENTRY"] ?? "/src/adapters/node",
preview: resolve("./dist/server/index.js"),
}),
!!process.env["VITEST"] && vitePluginTestReactServerStream(),
],

environments: {
Expand All @@ -57,6 +59,10 @@ export default defineConfig((_env) => ({
await build(builder.environments["ssr"]!);
},
},

test: {
dir: "src",
},
}));

// singleton to pass data through environment build
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
"tsx": "^4.7.1",
"typescript": "^5.4.3",
"vite": "6.0.0-alpha.3",
"vitest": "^1.5.1",
"wrangler": "^3.48.0"
},
"packageManager": "pnpm@8.15.5+sha256.4b4efa12490e5055d59b9b9fc9438b7d581a6b7af3b5675eb5c5f447cee1a589",
Expand Down
Loading