Skip to content

Commit

Permalink
Add unit tests for hono/context-storage
Browse files Browse the repository at this point in the history
  • Loading branch information
timokoessler committed Dec 6, 2024
1 parent 97d39ca commit ce503e5
Showing 1 changed file with 32 additions and 1 deletion.
33 changes: 32 additions & 1 deletion library/sources/Hono.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ import { isLocalhostIP } from "../helpers/isLocalhostIP";
import { createTestAgent } from "../helpers/createTestAgent";
import { addHonoMiddleware } from "../middleware/hono";
import * as fetch from "../helpers/fetch";
import {
contextStorage as honoContextStorage,
getContext as getHonoContext,
} from "hono/context-storage";

Check failure on line 18 in library/sources/Hono.test.ts

View workflow job for this annotation

GitHub Actions / build (18.x)

Unable to resolve path to module 'hono/context-storage'

wrap(fetch, "fetch", function mock(original) {
return async function mock(this: typeof fetch) {
Expand Down Expand Up @@ -62,11 +66,20 @@ const agent = createTestAgent({
});
agent.start([new HonoInternal(), new HTTPServer()]);

type Env = {
Variables: {
testProp: string;
};
};

function getApp() {
const { Hono } = require("hono") as typeof import("hono");
const app = new Hono();
const app = new Hono<Env>();

app.use(honoContextStorage());

app.use(async (c, next) => {
c.set("testProp", "test-value");
if (c.req.path.startsWith("/user/blocked")) {
setUser({ id: "567" });
} else if (c.req.path.startsWith("/user")) {
Expand All @@ -89,6 +102,15 @@ function getApp() {
return c.text("OK");
});

// Access async context outside of handler
const getTestProp = () => {
return getHonoContext<Env>().var.testProp;
};

app.get("/hono-async-context", (c) => {
return c.text(getTestProp());
});

return app;
}

Expand Down Expand Up @@ -335,3 +357,12 @@ t.test("ip blocking works (real socket)", opts, async (t) => {
// Cleanup server
server.close();
});

t.test("The hono async context still works", opts, async (t) => {
const response = await getApp().request("/hono-async-context", {
method: "GET",
});

const body = await response.text();
t.equal(body, "test-value");
});

0 comments on commit ce503e5

Please sign in to comment.