|
| 1 | +import { beforeEach, describe, expect, it, mock } from "bun:test"; |
| 2 | +import { HttpStatus } from "../../src"; |
| 3 | +import { openDb } from "./db"; |
| 4 | + |
| 5 | +// Mock any external dependencies |
| 6 | +mock.module("./dependencies", async () => { |
| 7 | + // In this case, use a real SQLite instance, but keep it in-memory |
| 8 | + const db = await openDb(":memory:"); |
| 9 | + |
| 10 | + return { db }; |
| 11 | +}); |
| 12 | + |
| 13 | +describe("App", async () => { |
| 14 | + // With bun:test, modules that depend on mocked modules or the mocked modules |
| 15 | + // themselves must be dynamically imported after the call to `mock.module`. |
| 16 | + const { app } = await import("./app"); |
| 17 | + const { db } = await import("./dependencies"); |
| 18 | + |
| 19 | + const fetch = app.build(); |
| 20 | + |
| 21 | + beforeEach(() => { |
| 22 | + // Reset the DB before each test |
| 23 | + db.run("DELETE FROM request_history"); |
| 24 | + }); |
| 25 | + |
| 26 | + it("should track all requests in SQLite", async () => { |
| 27 | + const url1 = new URL("http://localhost/one"); |
| 28 | + const url2 = new URL("http://localhost/two"); |
| 29 | + const url3 = new URL("http://localhost/three"); |
| 30 | + |
| 31 | + // Make the fetch requests |
| 32 | + await fetch(new Request(url1)); |
| 33 | + await fetch(new Request(url2)); |
| 34 | + await fetch(new Request(url3)); |
| 35 | + |
| 36 | + // Wait for onGlobalAfterResponse timeouts to be fired |
| 37 | + await Bun.sleep(1); |
| 38 | + |
| 39 | + const history = db |
| 40 | + .query("SELECT method, path, status_code FROM request_history") |
| 41 | + .all(); |
| 42 | + |
| 43 | + expect(history).toHaveLength(3); |
| 44 | + expect(history).toContainEqual({ |
| 45 | + method: "GET", |
| 46 | + path: "/one", |
| 47 | + status_code: HttpStatus.Ok, |
| 48 | + }); |
| 49 | + expect(history).toContainEqual({ |
| 50 | + method: "GET", |
| 51 | + path: "/two", |
| 52 | + status_code: HttpStatus.Ok, |
| 53 | + }); |
| 54 | + expect(history).toContainEqual({ |
| 55 | + method: "GET", |
| 56 | + path: "/three", |
| 57 | + status_code: HttpStatus.NotFound, |
| 58 | + }); |
| 59 | + }); |
| 60 | +}); |
0 commit comments