honojs / hono

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

`getConnInfo` fails in Bun tests #3460

Closed mrcaidev closed 1 month ago

mrcaidev commented 1 month ago

What version of Hono are you using?

4.6.3

What runtime/platform is your app running on?

Bun

What steps can reproduce the bug?

git clone https://github.com/mrcaidev/bun-hono-getconninfo-reproduction.git
cd bun-hono-getconninfo-reproduction
bun i
bun test

What is the expected behavior?

getConnInfo should not fail in testing environment.

What do you see instead?

bun test v1.1.29 (6d43b366)

src/index.test.ts:
1 | // src/adapter/bun/server.ts
2 | var getBunServer = (c) => "server" in c.env ? c.env.server : c.env;
                                          ^
TypeError: c.env is not an Object. (evaluating '"server" in c.env')
      at getBunServer (/home/mrcaidev/bun-hono-getconninfo-reproduction/node_modules/hono/dist/adapter/bun/server.js:2:39)
      at getConnInfo (/home/mrcaidev/bun-hono-getconninfo-reproduction/node_modules/hono/dist/adapter/bun/conninfo.js:4:18)
      at /home/mrcaidev/bun-hono-getconninfo-reproduction/src/index.ts:7:17
      at dispatch (/home/mrcaidev/bun-hono-getconninfo-reproduction/node_modules/hono/dist/hono-base.js:187:36)
      at /home/mrcaidev/bun-hono-getconninfo-reproduction/src/index.test.ts:6:27
      at /home/mrcaidev/bun-hono-getconninfo-reproduction/src/index.test.ts:5:26

2 | import app from './index'
3 | 
4 | describe('GET /', () => {
5 |   it('should return IP', async () => {
6 |     const res = await app.request('/')
7 |     expect(res.status).toEqual(200)
                           ^
error: expect(received).toEqual(expected)

Expected: 200
Received: 500

      at /home/mrcaidev/bun-hono-getconninfo-reproduction/src/index.test.ts:7:24
✗ GET / > should return IP [2.43ms]

 0 pass
 1 fail
 1 expect() calls
Ran 1 tests across 1 files. [66.00ms]

Additional information

Is it because Hono does not set up a real server when testing?

If it is, is there any workaround? Otherwise, I have to manually skip getConnInfo with process.env.NODE_ENV === "test" or similar codes every time.

yusukebe commented 1 month ago

Hi @mrcaidev

Is it because Hono does not set up a real server when testing?

Yes. But, you can pass the server info as a 3rd argument on app.request():

const res = await app.request(
  '/',
  {},
  {
    server: {
      requestIP: () => {
        return {
          address: '127.0.0.1',
          family: 'foo',
          port: '123'
        }
      }
    }
  }
)

It's like a workaround, but this is the best way.