diff --git a/docs/guides/testing.md b/docs/guides/testing.md index 37112247..28e6873f 100644 --- a/docs/guides/testing.md +++ b/docs/guides/testing.md @@ -128,3 +128,57 @@ test('GET /posts', async () => { const res = await app.request('/posts', {}, MOCK_ENV) }) ``` + +## Context + +To set values into your context `c.set()` for testing, create a custom testing middleware and add it before your test(s) run. + +For example, let's add a mock user object to "jwt" to all routes: + +```ts +const mockUser = { + id: "550e8400-e29b-41d4-a716-446655440000", + email: "johndoe@example.com", + age: 26 +}; + +// Create a Hono app instance and set middleware before each test +let app: Hono; +beforeEach(() => { + app = new Hono(); + + // Create a middleware and set any test data into the context + app.use("*", async (c, next) => { + c.set("user", mockUser); + await next(); + }); +}); + +``` + +Now during testing your context will have the mock object to which you can make assertions: +```ts +test('GET /friends', async () => { + // When the request is made, the c.get("user") will be the mockUser + const res = await app.request('/friends', {MOCK_ENV}) + expect(res.status).toBe(200) + expect(respository.getFriends).toHaveBeenCalledWith(mockUser.id); +}) +``` + +You can also test your route handlers, in this case you must **add the middleware before routing**: + +```ts +let app: Hono; +beforeEach(() => { + app = new Hono(); + + app.use("*", async (c, next) => { + // Make changes to your context + await next(); + }); + + // Routing after any middleware(s) + app.route("/", myHonoApp); +}); +``` \ No newline at end of file