Skip to content

test: improve tests#1204

Merged
chimurai merged 3 commits intomasterfrom
improve-tests
Apr 14, 2026
Merged

test: improve tests#1204
chimurai merged 3 commits intomasterfrom
improve-tests

Conversation

@chimurai
Copy link
Copy Markdown
Owner

@chimurai chimurai commented Apr 14, 2026

Summary by CodeRabbit

  • Tests

    • Introduced centralized test utilities for creating mock HTTP objects, replacing manual setup across unit tests.
    • Refactored end-to-end tests to use local mock servers instead of hardcoded URLs, improving test isolation and reliability.
  • Chores

    • Removed automatic test retry configuration to streamline test execution.

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Apr 14, 2026

📝 Walkthrough

Walkthrough

The pull request refactors test infrastructure across 18+ test files, replacing hardcoded http://localhost:${port} URLs with dynamically resolved mockTargetServer.url values and introducing shared test utility helpers (createMockRequest, createMockResponse, createMockClientRequest) for consistent HTTP mock object creation in unit and e2e tests.

Changes

Cohort / File(s) Summary
E2E tests with simplified URL references
test/e2e/hono.spec.ts, test/e2e/http-proxy-middleware.spec.ts, test/e2e/path-rewriter.spec.ts, test/e2e/plugins.spec.ts
Updated proxy target configuration to use mockTargetServer.url instead of constructing http://localhost:${mockTargetServer.port} strings. Also replaced inline HTTP stubs with createMockRequest/createMockResponse utilities where applicable.
E2E tests with local mock server provisioning
test/e2e/http-server.spec.ts, test/e2e/response-interceptor.spec.ts
Introduced beforeEach/afterEach lifecycle hooks to start/stop local Mockttp server instances. Replaced external service targets (httpbin.org) with local mock routes. Added node:zlib for compression testing and updated route stubs with async handling.
Router e2e test with URL-derived configuration
test/e2e/router.spec.ts
Removed dynamic port allocation; updated router configuration to derive host, port, and protocol from targetServer.url using new URL() parsing instead of hardcoded literals. Eliminated get-port dependency for test targets.
WebSocket e2e test with mock server replacement
test/e2e/websocket.spec.ts
Replaced real WebSocketServer with Mockttp-backed echo target (mockWsTargetServer). Added toWebSocketUrl() helper for WS URL derivation. Switched inline mock objects to shared createMockRequest/createMockResponse utilities.
Test utility helpers
test/test-utils.ts
New file exporting three factory functions: createMockRequest() (constructs IncomingMessage with Socket), createMockResponse() (builds ServerResponse with Vitest spies), and createMockClientRequest() (instantiates ClientRequest with mocked emit and spied methods).
Unit tests refactoring
test/unit/fix-request-body.spec.ts, test/unit/path-filter.spec.ts, test/unit/path-rewriter.spec.ts, test/unit/response-interceptor.spec.ts, test/unit/router.spec.ts
Replaced manual Node HTTP/NET object construction (IncomingMessage, ServerResponse, Socket) with shared createMockRequest() and createMockResponse() helpers. Removed inline vi.fn() mocking in favor of built-in mock implementations.
Utility unit test
test/unit/utils/function.spec.ts
Updated arrow function test case constant name from myFunction to myArrowFunction with corresponding assertion update.
Build configuration
vitest.config.ts
Removed test.retry: 3 configuration line.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~30 minutes

Possibly related PRs

Poem

🐰 Mock servers sprout where hardcoded URLs once grew,
Test helpers bloom across the suite so true,
No more localhost:${port} in sight,
Dynamic discovery makes testing right! ✨

🚥 Pre-merge checks | ✅ 1 | ❌ 2

❌ Failed checks (1 warning, 1 inconclusive)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
Title check ❓ Inconclusive The title 'test: improve tests' is overly vague and generic. It doesn't convey meaningful information about the actual changes, which involve replacing external test dependencies with local mock servers and refactoring test utilities across multiple test files. Use a more descriptive title that captures the main change, such as 'test: replace external dependencies with local mock servers' or 'test: refactor with shared mock utilities and mockttp'.
✅ Passed checks (1 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch improve-tests

Comment @coderabbitai help to get the list of available commands and usage tips.

@chimurai chimurai changed the title test(path-rewriter): remove as any test: improve tests Apr 14, 2026
@pkg-pr-new
Copy link
Copy Markdown

pkg-pr-new Bot commented Apr 14, 2026

npm i https://pkg.pr.new/http-proxy-middleware@1204

commit: ee444f1

@coveralls
Copy link
Copy Markdown

Coverage Status

coverage: 93.103%. remained the same — improve-tests into master

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (3)
test/test-utils.ts (1)

24-33: Use vi.spyOn() for emit to maintain consistency and preserve EventEmitter return behavior.

Line 29 replaces emit outright with vi.fn(), unlike the other methods on lines 31–33 which use vi.spyOn(). This inconsistency also drops the method's boolean return value. While the current test doesn't depend on this, use vi.spyOn(clientRequest, 'emit').mockImplementation(() => true) to keep the pattern consistent and avoid masking potential event-flow issues.

Suggested patch
 export function createMockClientRequest(
   ...args: ConstructorParameters<typeof ClientRequest>
 ): ClientRequest {
   const clientRequest = new ClientRequest(...args);
 
-  clientRequest.emit = vi.fn();
+  vi.spyOn(clientRequest, 'emit').mockImplementation(() => true);
 
   vi.spyOn(clientRequest, 'setHeader');
   vi.spyOn(clientRequest, 'write');
   vi.spyOn(clientRequest, 'destroy');
 
   return clientRequest;
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/test-utils.ts` around lines 24 - 33, The test helper
createMockClientRequest currently replaces clientRequest.emit with vi.fn(),
breaking consistency and losing the EventEmitter boolean return; change that to
use vi.spyOn(clientRequest, 'emit').mockImplementation(() => true) instead of
direct assignment, keeping the other spies (setHeader, write, destroy) as-is so
emit preserves its return value and follows the same spy pattern.
test/e2e/router.spec.ts (1)

123-139: Test name may be stale after refactoring.

The test is named "missing a ':' in protocol will cause it to use https" but the implementation now uses target.protocol which includes the colon (e.g., "https:"). The test still passes because HTTPS is used, but the name no longer reflects what's being tested.

Consider renaming to better reflect the current behavior:

📝 Proposed name update
-    it('missing a ":" in protocol will cause it to use https', async () => {
+    it('should work with URL-derived protocol', async () => {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/e2e/router.spec.ts` around lines 123 - 139, Rename the test case whose
title is "missing a ':' in protocol will cause it to use https" to accurately
reflect that the router callback returns target.protocol (which includes the
colon, e.g., "https:"), for example "router returning protocol with colon uses
https" or similar; update the it(...) description where createProxyMiddleware is
invoked and the router callback returns { host: target.hostname, port:
target.port, protocol: target.protocol } so the test name matches the actual
behavior being asserted.
test/unit/fix-request-body.spec.ts (1)

160-176: proxyResponse is unused in this test.

The proxyResponse mock is created on line 168 but is never passed to fixRequestBody(). The assertion on line 173 (expect(proxyResponse.end).toHaveBeenCalledTimes(0)) will always pass trivially since proxyResponse is not involved in the function under test.

Consider removing this dead code or clarifying the test intent:

♻️ Proposed fix to remove unused mock
   it('should not fixRequestBody() when there bodyParser fails', () => {
     const proxyRequest = fakeProxyRequest();
     const request = {
       get readableLength() {
         return 4444; // simulate bodyParser failure
       },
     } as BodyParserLikeRequest;

-    const proxyResponse = createMockResponse();
     proxyRequest.setHeader('content-type', 'application/x-www-form-urlencoded');

     fixRequestBody(proxyRequest, request);

-    expect(proxyResponse.end).toHaveBeenCalledTimes(0);
     expect(proxyRequest.write).toHaveBeenCalledTimes(0);
     expect(proxyRequest.destroy).toHaveBeenCalledTimes(0);
   });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/unit/fix-request-body.spec.ts` around lines 160 - 176, The test creates
an unused proxyResponse mock and asserts on it even though
fixRequestBody(proxyRequest, request) never receives it; remove the dead
proxyResponse variable and its assertion (expect(proxyResponse.end)...), or if
you intended to assert behavior on the response, pass that mock into
fixRequestBody and update the function call accordingly. Locate the
proxyResponse declaration in the test and either delete its creation and the
expect(proxyResponse.end).toHaveBeenCalledTimes(0) line, or change the call to
fixRequestBody(proxyRequest, request, proxyResponse) and adjust fixRequestBody
to accept and use that third parameter.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@test/e2e/router.spec.ts`:
- Around line 123-139: Rename the test case whose title is "missing a ':' in
protocol will cause it to use https" to accurately reflect that the router
callback returns target.protocol (which includes the colon, e.g., "https:"), for
example "router returning protocol with colon uses https" or similar; update the
it(...) description where createProxyMiddleware is invoked and the router
callback returns { host: target.hostname, port: target.port, protocol:
target.protocol } so the test name matches the actual behavior being asserted.

In `@test/test-utils.ts`:
- Around line 24-33: The test helper createMockClientRequest currently replaces
clientRequest.emit with vi.fn(), breaking consistency and losing the
EventEmitter boolean return; change that to use vi.spyOn(clientRequest,
'emit').mockImplementation(() => true) instead of direct assignment, keeping the
other spies (setHeader, write, destroy) as-is so emit preserves its return value
and follows the same spy pattern.

In `@test/unit/fix-request-body.spec.ts`:
- Around line 160-176: The test creates an unused proxyResponse mock and asserts
on it even though fixRequestBody(proxyRequest, request) never receives it;
remove the dead proxyResponse variable and its assertion
(expect(proxyResponse.end)...), or if you intended to assert behavior on the
response, pass that mock into fixRequestBody and update the function call
accordingly. Locate the proxyResponse declaration in the test and either delete
its creation and the expect(proxyResponse.end).toHaveBeenCalledTimes(0) line, or
change the call to fixRequestBody(proxyRequest, request, proxyResponse) and
adjust fixRequestBody to accept and use that third parameter.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: a58b97b3-1385-4d10-9d6d-fddfc829b614

📥 Commits

Reviewing files that changed from the base of the PR and between a4f0821 and ee444f1.

📒 Files selected for processing (16)
  • test/e2e/hono.spec.ts
  • test/e2e/http-proxy-middleware.spec.ts
  • test/e2e/http-server.spec.ts
  • test/e2e/path-rewriter.spec.ts
  • test/e2e/plugins.spec.ts
  • test/e2e/response-interceptor.spec.ts
  • test/e2e/router.spec.ts
  • test/e2e/websocket.spec.ts
  • test/test-utils.ts
  • test/unit/fix-request-body.spec.ts
  • test/unit/path-filter.spec.ts
  • test/unit/path-rewriter.spec.ts
  • test/unit/response-interceptor.spec.ts
  • test/unit/router.spec.ts
  • test/unit/utils/function.spec.ts
  • vitest.config.ts
💤 Files with no reviewable changes (1)
  • vitest.config.ts

@chimurai chimurai merged commit 222e1f7 into master Apr 14, 2026
21 checks passed
@chimurai chimurai deleted the improve-tests branch April 14, 2026 20:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants