honojs / hono

Web framework built on Web Standards
https://hono.dev
MIT License
18.28k stars 515 forks source link

Hono doesn't consider status codes from middlewares with `testClient` #3170

Open cybercoder-naj opened 1 month ago

cybercoder-naj commented 1 month ago

What version of Hono are you using?

4.4.9

What runtime/platform is your app running on?

Bun

What steps can reproduce the bug?

// index.ts
import { Hono } from "hono";
import { logger } from "hono/logger";
import { createFactory } from "hono/factory";

const factory = createFactory();

const myMiddleware = () => {
  return factory.createMiddleware(async (c, next) => {
    const random = Math.random();
    if (random > 0.5) {
      c.status(500);
      return c.text("Probabilistic error", 500);
    }
    return next();
  });
};

const app = new Hono().use(logger()).get("/", myMiddleware(), async (c) => {
  return c.json({ message: "Hello, World!" }, 200);
});

export default app;

// index.test.ts
import { test, expect } from "bun:test";
import app from ".";
import { testClient } from "hono/testing";

test("GET /", async () => {
  const res = await testClient(app).index.$get();

  expect(res.status).toBe(500); // <- "Argument of type '500' is not assignable to parameter of type '200'"
});

What is the expected behavior?

Consider other status codes that may be returned from middlewares or other factors.

What do you see instead?

Argument of type '500' is not assignable to parameter of type '200'

Additional information

No response

yusukebe commented 1 month ago

Hi @cybercoder-naj

I can't understand your problem. The res.status will be 500 or 200, so it's no problem.

cybercoder-naj commented 1 month ago

The middleware returns status code 500 but the route handler itself only returns 200. So when I'm trying to test the app with the route and assert the status code, Typescript only allows me to test on 200. Is that making sense?

Since the route handler only returns a status code of 200, res.status in the test doesn't have type 200 | 500. The type is simply 200.

Either I have to add // @ts-ignore or let vscode show it's a Typescript error

yusukebe commented 1 month ago

@cybercoder-naj

Ah! It's about TypeScript types! You are right. It's like a bug but a known issue similar to https://github.com/honojs/middleware/issues/580

There is no solution to remove the error immediately, but I'll find a good way. Thanks!

cybercoder-naj commented 1 month ago

Yesss. It's the same issue essentially. Should I mark this closed as duplicate?

yusukebe commented 1 month ago

Should I mark this closed as duplicate?

No! It's a little bit difference from this issue. Let's keep it.

yusukebe commented 1 month ago

Hi @kosei28

What do you think of these problems? Any thoughts?

KaelWD commented 1 month ago

2719