Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Testing: Add Context section #416

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
54 changes: 54 additions & 0 deletions docs/guides/testing.md
Original file line number Diff line number Diff line change
Expand Up @@ -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: "[email protected]",
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);
});
```