Testing utilities for QuickJS runtime
npm install @ricsam/quickjs-test-utilsTesting utilities including type checking for QuickJS user code.
``bash`
bun add @ricsam/quickjs-test-utils
Validate TypeScript/JavaScript code that will run inside QuickJS before execution using ts-morph:
`typescript
import { typecheckQuickJSCode } from "@ricsam/quickjs-test-utils";
const result = typecheckQuickJSCode(
serve({
fetch(request, server) {
const url = new URL(request.url);
if (url.pathname === "/ws") {
server.upgrade(request, { data: { userId: 123 } });
return new Response(null, { status: 101 });
}
return Response.json({ message: "Hello!" });
},
websocket: {
message(ws, message) {
ws.send("Echo: " + message);
}
}
});, { include: ["core", "fetch"] });
if (!result.success) {
console.error("Type errors found:");
for (const error of result.errors) {
console.error( Line ${error.line}: ${error.message});`
}
}
| Option | Description |
|--------|-------------|
| include | Which package types to include: "core", "fetch", "fs" (default: all) |compilerOptions
| | Additional TypeScript compiler options |
`typescript
import { describe, expect, test } from "bun:test";
import { typecheckQuickJSCode } from "@ricsam/quickjs-test-utils";
describe("QuickJS code validation", () => {
test("server code is type-safe", () => {
const result = typecheckQuickJSCode(userProvidedCode, {
include: ["fetch"]
});
expect(result.success).toBe(true);
});
});
`
The type definitions are also exported as strings for custom use cases:
`typescript
import {
CORE_TYPES, // ReadableStream, Blob, File, URL, etc.
FETCH_TYPES, // fetch, Request, Response, serve, etc.
FS_TYPES, // getDirectory, FileSystemHandle, etc.
CRYPTO_TYPES, // crypto.subtle, CryptoKey, etc.
TYPE_DEFINITIONS // All types as { core, fetch, fs, crypto, ... }
} from "@ricsam/quickjs-test-utils";
// Use with your own ts-morph project
project.createSourceFile("quickjs-globals.d.ts", FETCH_TYPES);
`
Each package also exports .d.ts files for use with tsconfig.json:
`json``
{
"compilerOptions": {
"lib": ["ESNext", "DOM"]
},
"include": ["quickjs-code/*/.ts"],
"references": [
{ "path": "./node_modules/@ricsam/quickjs-core/src/quickjs.d.ts" },
{ "path": "./node_modules/@ricsam/quickjs-fetch/src/quickjs.d.ts" },
{ "path": "./node_modules/@ricsam/quickjs-fs/src/quickjs.d.ts" },
{ "path": "./node_modules/@ricsam/quickjs-crypto/src/quickjs.d.ts" }
]
}