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

Cannot mock the result of env(c) on NodeJS #3895

Open
lachesis opened this issue Feb 6, 2025 · 0 comments
Open

Cannot mock the result of env(c) on NodeJS #3895

lachesis opened this issue Feb 6, 2025 · 0 comments
Labels

Comments

@lachesis
Copy link

lachesis commented Feb 6, 2025

What version of Hono are you using?

4.6.20

What runtime/platform is your app running on? (with version if possible)

Node.js/23

What steps can reproduce the bug?

I'm developing a program that needs to run on both Cloudflare Workers and Node.js (on-prem). To handle this, I'm using the env() helper from hono/adapter. However, this interact poorly with testing using app.request, as it mocks c.env, but that does not affect env(c) on the NodeJS runtime.

To reproduce, create the following file under the path test/index.js:

import 'mocha'
import { assert, expect } from 'chai'

import { env } from 'hono/adapter'
import { Hono } from 'hono'

const app = new Hono()

app.get('/', (c) => {
  return c.text(`Var is ${env(c).VAR}`)
})

describe('Example', () => {
  it('GET /', async () => {
    const res = await app.request('/', {}, {VAR: "abc"})
    expect(res.status).to.equal(200)
    expect(await res.text()).to.equal('Var is abc')
  })
})

use the following package.json:

{
  "name": "my-app",
  "type": "module",
  "scripts": {
    "dev": "tsx watch src/index.ts",
    "test": "tsc && mocha"
  },
  "dependencies": {
    "@hono/node-server": "^1.13.8",
    "chai": "^5.1.2",
    "hono": "^4.6.20",
    "mocha": "^11.1.0",
    "tsc": "^2.0.4",
    "typescript": "^5.7.3"
  },
  "devDependencies": {
    "@types/node": "^20.11.17",
    "tsx": "^4.7.1"
  }
}

run the following command, which will both build and test the project:

npm run test

What is the expected behavior?

> test
> tsc && mocha



  Example
    ✔ GET /


  1 passing (18ms)

What do you see instead?

> test
> tsc && mocha



  Example
    1) GET /


  0 passing (17ms)
  1 failing

  1) Example
       GET /:

      AssertionError: expected 'Var is undefined' to equal 'Var is abc'
      + expected - actual

      -Var is undefined
      +Var is abc

Additional information

The global environment passes through unmocked, so you can see the expected output by running:

VAR=abc npm run test
@lachesis lachesis added the triage label Feb 6, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant