Replies: 1 comment
-
Create a app.ts: import { Hono } from "hono";
import type { Logger } from "pino";
export type Deps = {
logger: Logger;
};
export const app = new Hono<{
Variables: Deps;
}>();
app.get("/ping", (c) => {
c.get("logger").info("pinging");
return c.json({ pong: true });
}); app.test.ts: import { Hono } from "hono";
import type { Logger } from "pino";
import { expect, test, vi } from "vitest";
import { type Deps, app } from "./app.js";
const getAppWithMockedDeps = () => {
const testDeps = {
logger: {
info: vi.fn(),
} as unknown as Logger,
};
const appWithTestDeps = new Hono<{ Variables: Deps }>();
appWithTestDeps
.use(async (c, next) => {
c.set("logger", testDeps.logger);
await next();
})
.route("/", app);
return { app: appWithTestDeps, deps: testDeps };
};
test("logs when pinging", async () => {
const { app, deps } = getAppWithMockedDeps();
await app.request("/ping");
expect(deps.logger.info).toHaveBeenCalled();
}); @yusukebe would be nice to have something like this in the docs, the ability to test handlers without starting a server was one of the things that attracted me to Hono, but when it was time to write tests, it wasn't at all obvious how to inject dependencies. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I have some code as follows:
I'm thinking that testing would be much simpler if I could inject dependencies into the Context.
Is there a way to do this?
Beta Was this translation helpful? Give feedback.
All reactions