cf-bun-mocks 0.1.0-alpha.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +161 -0
- package/package.json +42 -0
- package/src/d1.ts +186 -0
- package/src/env.ts +15 -0
- package/src/index.ts +2 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Dan Lilienblum
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
# cf-bun-mocks
|
|
2
|
+
|
|
3
|
+
Cloudflare Workers mocks and helpers for Bun testing.
|
|
4
|
+
|
|
5
|
+
## Installation
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
bun add -d cf-bun-mocks
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## D1 Mock
|
|
12
|
+
|
|
13
|
+
The D1 mock provides a drop-in replacement for Cloudflare's D1 database, backed by Bun's native SQLite.
|
|
14
|
+
|
|
15
|
+
### Basic Usage
|
|
16
|
+
|
|
17
|
+
```typescript
|
|
18
|
+
import { D1Mock } from "cf-bun-mocks";
|
|
19
|
+
|
|
20
|
+
// In-memory database (recommended for tests)
|
|
21
|
+
const db = new D1Mock(":memory:");
|
|
22
|
+
|
|
23
|
+
// Or persist to a file
|
|
24
|
+
const db = new D1Mock("./test.db");
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
### With Migrations
|
|
28
|
+
|
|
29
|
+
Use `initD1` to create an in-memory database and run your migrations:
|
|
30
|
+
|
|
31
|
+
```typescript
|
|
32
|
+
import { initD1 } from "cf-bun-mocks";
|
|
33
|
+
|
|
34
|
+
const db = await initD1("./migrations");
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
This reads all `.sql` files from the migrations directory in sorted order and executes them.
|
|
38
|
+
|
|
39
|
+
### Example Test
|
|
40
|
+
|
|
41
|
+
```typescript
|
|
42
|
+
import { describe, test, expect, beforeEach } from "bun:test";
|
|
43
|
+
import { D1Mock } from "cf-bun-mocks";
|
|
44
|
+
import type { D1Database } from "@cloudflare/workers-types";
|
|
45
|
+
|
|
46
|
+
describe("my worker", () => {
|
|
47
|
+
let db: D1Database;
|
|
48
|
+
|
|
49
|
+
beforeEach(async () => {
|
|
50
|
+
db = new D1Mock(":memory:");
|
|
51
|
+
await db.exec(`
|
|
52
|
+
CREATE TABLE users (
|
|
53
|
+
id INTEGER PRIMARY KEY,
|
|
54
|
+
name TEXT NOT NULL,
|
|
55
|
+
email TEXT UNIQUE
|
|
56
|
+
)
|
|
57
|
+
`);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
test("insert and query", async () => {
|
|
61
|
+
await db
|
|
62
|
+
.prepare("INSERT INTO users (name, email) VALUES (?, ?)")
|
|
63
|
+
.bind("Alice", "alice@example.com")
|
|
64
|
+
.run();
|
|
65
|
+
|
|
66
|
+
const user = await db
|
|
67
|
+
.prepare("SELECT * FROM users WHERE email = ?")
|
|
68
|
+
.bind("alice@example.com")
|
|
69
|
+
.first();
|
|
70
|
+
|
|
71
|
+
expect(user).toEqual({
|
|
72
|
+
id: 1,
|
|
73
|
+
name: "Alice",
|
|
74
|
+
email: "alice@example.com",
|
|
75
|
+
});
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
test("batch operations", async () => {
|
|
79
|
+
const results = await db.batch([
|
|
80
|
+
db
|
|
81
|
+
.prepare("INSERT INTO users (name, email) VALUES (?, ?)")
|
|
82
|
+
.bind("Bob", "bob@example.com"),
|
|
83
|
+
db
|
|
84
|
+
.prepare("INSERT INTO users (name, email) VALUES (?, ?)")
|
|
85
|
+
.bind("Carol", "carol@example.com"),
|
|
86
|
+
db.prepare("SELECT * FROM users"),
|
|
87
|
+
]);
|
|
88
|
+
|
|
89
|
+
expect(results[2].results).toHaveLength(2);
|
|
90
|
+
});
|
|
91
|
+
});
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
### Injecting into Workers
|
|
95
|
+
|
|
96
|
+
Pass the mock as your D1 binding when testing your worker:
|
|
97
|
+
|
|
98
|
+
```typescript
|
|
99
|
+
import { D1Mock } from "cf-bun-mocks";
|
|
100
|
+
import type { Env } from "./worker";
|
|
101
|
+
|
|
102
|
+
const env: Env = {
|
|
103
|
+
DB: new D1Mock(":memory:"),
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
// Test your worker with the mock env
|
|
107
|
+
const response = await worker.fetch(request, env);
|
|
108
|
+
```
|
|
109
|
+
|
|
110
|
+
## Environment Mock
|
|
111
|
+
|
|
112
|
+
Use `useEnv` to mock `cloudflare:env` imports in your tests:
|
|
113
|
+
|
|
114
|
+
```typescript
|
|
115
|
+
import { describe, test, expect } from "bun:test";
|
|
116
|
+
import { useEnv, D1Mock } from "cf-bun-mocks";
|
|
117
|
+
import type { Env } from "./worker";
|
|
118
|
+
|
|
119
|
+
describe("my worker", () => {
|
|
120
|
+
useEnv<Env>(async () => ({
|
|
121
|
+
DB: new D1Mock(":memory:"),
|
|
122
|
+
MY_SECRET: "test-secret",
|
|
123
|
+
}));
|
|
124
|
+
|
|
125
|
+
test("uses mocked env", async () => {
|
|
126
|
+
// Your worker code that imports from "cloudflare:env" will get the mock
|
|
127
|
+
const { myFunction } = await import("./worker");
|
|
128
|
+
const result = await myFunction();
|
|
129
|
+
expect(result).toBeDefined();
|
|
130
|
+
});
|
|
131
|
+
});
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
## API
|
|
135
|
+
|
|
136
|
+
### `D1Mock`
|
|
137
|
+
|
|
138
|
+
Implements the full `D1Database` interface from `@cloudflare/workers-types`:
|
|
139
|
+
|
|
140
|
+
- `prepare(query: string)` - Create a prepared statement
|
|
141
|
+
- `batch(statements: D1PreparedStatement[])` - Execute multiple statements
|
|
142
|
+
- `exec(query: string)` - Execute raw SQL
|
|
143
|
+
- `dump()` - Serialize the database to an ArrayBuffer
|
|
144
|
+
- `withSession(constraint?)` - Get a session (bookmark tracking is stubbed)
|
|
145
|
+
|
|
146
|
+
### `initD1(migrationsPath: string)`
|
|
147
|
+
|
|
148
|
+
Creates an in-memory D1Mock and runs all `.sql` files from the specified directory.
|
|
149
|
+
|
|
150
|
+
### `useEnv<TEnv>(setup: () => TEnv | Promise<TEnv>)`
|
|
151
|
+
|
|
152
|
+
Registers `beforeEach`/`afterEach` hooks to mock `cloudflare:env` for each test. Call at the top of your `describe` block.
|
|
153
|
+
|
|
154
|
+
## Requirements
|
|
155
|
+
|
|
156
|
+
- Bun v1.0+
|
|
157
|
+
- TypeScript 5+
|
|
158
|
+
|
|
159
|
+
## License
|
|
160
|
+
|
|
161
|
+
MIT
|
package/package.json
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "cf-bun-mocks",
|
|
3
|
+
"version": "0.1.0-alpha.0",
|
|
4
|
+
"description": "Cloudflare Workers mocks and helpers for Bun testing",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"main": "src/index.ts",
|
|
7
|
+
"module": "src/index.ts",
|
|
8
|
+
"types": "src/index.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"import": "./src/index.ts",
|
|
12
|
+
"types": "./src/index.ts"
|
|
13
|
+
},
|
|
14
|
+
"./d1": {
|
|
15
|
+
"import": "./src/d1.ts",
|
|
16
|
+
"types": "./src/d1.ts"
|
|
17
|
+
},
|
|
18
|
+
"./env": {
|
|
19
|
+
"import": "./src/env.ts",
|
|
20
|
+
"types": "./src/env.ts"
|
|
21
|
+
}
|
|
22
|
+
},
|
|
23
|
+
"files": [
|
|
24
|
+
"src"
|
|
25
|
+
],
|
|
26
|
+
"keywords": [
|
|
27
|
+
"cloudflare",
|
|
28
|
+
"workers",
|
|
29
|
+
"d1",
|
|
30
|
+
"mock",
|
|
31
|
+
"bun",
|
|
32
|
+
"testing"
|
|
33
|
+
],
|
|
34
|
+
"license": "MIT",
|
|
35
|
+
"devDependencies": {
|
|
36
|
+
"@cloudflare/workers-types": "^4.20260103.0",
|
|
37
|
+
"@types/bun": "latest"
|
|
38
|
+
},
|
|
39
|
+
"peerDependencies": {
|
|
40
|
+
"typescript": "^5"
|
|
41
|
+
}
|
|
42
|
+
}
|
package/src/d1.ts
ADDED
|
@@ -0,0 +1,186 @@
|
|
|
1
|
+
import { Database, type SQLQueryBindings } from "bun:sqlite";
|
|
2
|
+
import { readdirSync } from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import type {
|
|
5
|
+
D1PreparedStatement,
|
|
6
|
+
D1Result,
|
|
7
|
+
D1Database,
|
|
8
|
+
D1DatabaseSession,
|
|
9
|
+
D1SessionBookmark,
|
|
10
|
+
D1SessionConstraint,
|
|
11
|
+
D1ExecResult,
|
|
12
|
+
} from "@cloudflare/workers-types";
|
|
13
|
+
|
|
14
|
+
class D1PreparedStatementMock implements D1PreparedStatement {
|
|
15
|
+
#stmt: ReturnType<Database["prepare"]>;
|
|
16
|
+
#boundValues: SQLQueryBindings[] = [];
|
|
17
|
+
|
|
18
|
+
constructor(stmt: ReturnType<Database["prepare"]>) {
|
|
19
|
+
this.#stmt = stmt;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
bind(...values: unknown[]): D1PreparedStatement {
|
|
23
|
+
this.#boundValues = values as SQLQueryBindings[];
|
|
24
|
+
return this as D1PreparedStatement;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
async first<T = Record<string, unknown>>(
|
|
28
|
+
colName?: string
|
|
29
|
+
): Promise<T | null> {
|
|
30
|
+
const result = this.#stmt.get(...this.#boundValues);
|
|
31
|
+
if (result === null || result === undefined) {
|
|
32
|
+
return null;
|
|
33
|
+
}
|
|
34
|
+
if (colName) {
|
|
35
|
+
return (result as Record<string, unknown>)[colName] as T;
|
|
36
|
+
}
|
|
37
|
+
return result as T;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
async run<T = Record<string, unknown>>(): Promise<D1Result<T>> {
|
|
41
|
+
const changes = this.#stmt.run(...this.#boundValues);
|
|
42
|
+
return {
|
|
43
|
+
success: true,
|
|
44
|
+
meta: {
|
|
45
|
+
duration: 0,
|
|
46
|
+
size_after: 0,
|
|
47
|
+
rows_read: 0,
|
|
48
|
+
rows_written: changes.changes,
|
|
49
|
+
last_row_id: Number(changes.lastInsertRowid),
|
|
50
|
+
changed_db: changes.changes > 0,
|
|
51
|
+
changes: changes.changes,
|
|
52
|
+
},
|
|
53
|
+
results: [] as T[],
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async all<T = Record<string, unknown>>(): Promise<D1Result<T>> {
|
|
58
|
+
const results = this.#stmt.all(...this.#boundValues);
|
|
59
|
+
return {
|
|
60
|
+
success: true,
|
|
61
|
+
meta: {
|
|
62
|
+
duration: 0,
|
|
63
|
+
size_after: 0,
|
|
64
|
+
rows_read: results.length,
|
|
65
|
+
rows_written: 0,
|
|
66
|
+
last_row_id: 0,
|
|
67
|
+
changed_db: false,
|
|
68
|
+
changes: 0,
|
|
69
|
+
},
|
|
70
|
+
results: results as T[],
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async raw<T = unknown[]>(options: {
|
|
75
|
+
columnNames: true;
|
|
76
|
+
}): Promise<[string[], ...T[]]>;
|
|
77
|
+
async raw<T = unknown[]>(options?: { columnNames?: false }): Promise<T[]>;
|
|
78
|
+
async raw<T = unknown[]>(options?: {
|
|
79
|
+
columnNames?: boolean;
|
|
80
|
+
}): Promise<T[] | [string[], ...T[]]> {
|
|
81
|
+
const values = this.#stmt.values(...this.#boundValues);
|
|
82
|
+
if (options?.columnNames) {
|
|
83
|
+
return [this.#stmt.columnNames, ...(values as T[])] as [string[], ...T[]];
|
|
84
|
+
}
|
|
85
|
+
return values as T[];
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
class D1DatabaseSessionMock implements D1DatabaseSession {
|
|
90
|
+
#db: D1Mock;
|
|
91
|
+
#bookmark: D1SessionBookmark | null = null;
|
|
92
|
+
|
|
93
|
+
constructor(db: D1Mock) {
|
|
94
|
+
this.#db = db;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
prepare(query: string): D1PreparedStatement {
|
|
98
|
+
return this.#db.prepare(query);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
async batch<T = unknown>(
|
|
102
|
+
statements: D1PreparedStatement[]
|
|
103
|
+
): Promise<D1Result<T>[]> {
|
|
104
|
+
return this.#db.batch(statements);
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
getBookmark(): D1SessionBookmark | null {
|
|
108
|
+
return this.#bookmark;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
export class D1Mock implements D1Database {
|
|
113
|
+
#db: Database;
|
|
114
|
+
|
|
115
|
+
constructor(
|
|
116
|
+
filename?: string,
|
|
117
|
+
options?:
|
|
118
|
+
| number
|
|
119
|
+
| {
|
|
120
|
+
readonly?: boolean;
|
|
121
|
+
create?: boolean;
|
|
122
|
+
readwrite?: boolean;
|
|
123
|
+
safeIntegers?: boolean;
|
|
124
|
+
strict?: boolean;
|
|
125
|
+
}
|
|
126
|
+
) {
|
|
127
|
+
this.#db = new Database(filename, options);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
prepare(query: string): D1PreparedStatement {
|
|
131
|
+
const stmt = this.#db.prepare(query);
|
|
132
|
+
return new D1PreparedStatementMock(stmt);
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async batch<T = unknown>(
|
|
136
|
+
statements: D1PreparedStatement[]
|
|
137
|
+
): Promise<D1Result<T>[]> {
|
|
138
|
+
const results: D1Result<T>[] = [];
|
|
139
|
+
for (const stmt of statements) {
|
|
140
|
+
if (stmt instanceof D1PreparedStatementMock) {
|
|
141
|
+
const result = await stmt.all<T>();
|
|
142
|
+
results.push(result);
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return results;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async exec(query: string): Promise<D1ExecResult> {
|
|
149
|
+
const start = performance.now();
|
|
150
|
+
const { changes: count } = this.#db.run(query);
|
|
151
|
+
const duration = performance.now() - start;
|
|
152
|
+
return {
|
|
153
|
+
count,
|
|
154
|
+
duration,
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
withSession(
|
|
159
|
+
_constraintOrBookmark?: D1SessionBookmark | D1SessionConstraint
|
|
160
|
+
): D1DatabaseSession {
|
|
161
|
+
return new D1DatabaseSessionMock(this);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
async dump(): Promise<ArrayBuffer> {
|
|
165
|
+
const serialized = this.#db.serialize();
|
|
166
|
+
const buffer = serialized.buffer;
|
|
167
|
+
if (buffer instanceof SharedArrayBuffer) {
|
|
168
|
+
const newBuffer = new ArrayBuffer(buffer.byteLength);
|
|
169
|
+
new Uint8Array(newBuffer).set(new Uint8Array(buffer));
|
|
170
|
+
return newBuffer;
|
|
171
|
+
}
|
|
172
|
+
return buffer;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export async function initD1(migrationsPath: string): Promise<D1Mock> {
|
|
177
|
+
const files = readdirSync(migrationsPath)
|
|
178
|
+
.filter((file) => file.endsWith(".sql"))
|
|
179
|
+
.sort();
|
|
180
|
+
const db = new D1Mock(":memory:");
|
|
181
|
+
for (const file of files) {
|
|
182
|
+
const migration = await Bun.file(path.join(migrationsPath, file)).text();
|
|
183
|
+
await db.exec(migration);
|
|
184
|
+
}
|
|
185
|
+
return db;
|
|
186
|
+
}
|
package/src/env.ts
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/// <reference types="@cloudflare/workers-types" />
|
|
2
|
+
import { beforeEach, afterEach, mock } from "bun:test";
|
|
3
|
+
|
|
4
|
+
export function useEnv<TEnv extends Cloudflare.Env = Cloudflare.Env>(
|
|
5
|
+
setup: () => Bun.MaybePromise<TEnv>
|
|
6
|
+
) {
|
|
7
|
+
beforeEach(async () => {
|
|
8
|
+
const env = await setup();
|
|
9
|
+
mock.module("cloudflare:env", () => env);
|
|
10
|
+
});
|
|
11
|
+
|
|
12
|
+
afterEach(() => {
|
|
13
|
+
mock.module("cloudflare:env", () => {});
|
|
14
|
+
});
|
|
15
|
+
}
|
package/src/index.ts
ADDED