Skip to content

Add comprehensive unit tests for http-helpers.ts#158

Draft
Dexploarer wants to merge 1 commit intodevelopfrom
test-http-helpers-3796730622032416101
Draft

Add comprehensive unit tests for http-helpers.ts#158
Dexploarer wants to merge 1 commit intodevelopfrom
test-http-helpers-3796730622032416101

Conversation

@Dexploarer
Copy link
Owner

Implements unit tests for the core HTTP helpers module (src/api/http-helpers.ts). Checks stream behavior, request payload limits, flag behavior like returnNullOnTooLarge, error handling, and JSON serialization defaults. Matches the existing test paradigms and ensures coverage without modifying production code.


PR created automatically by Jules for task 3796730622032416101 started by @Dexploarer

Adds a complete unit testing suite for the HTTP utility functions
provided in `src/api/http-helpers.ts`. Ensures that stream behavior,
JSON parsing, and edge cases (e.g. maximum body limits, invalid JSON,
and various error flags) are properly validated without touching
any production logic.
@google-labs-jules
Copy link

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@coderabbitai
Copy link

coderabbitai bot commented Feb 28, 2026

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch test-http-helpers-3796730622032416101

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

Comment on lines +23 to +32
process.nextTick(() => {
for (const chunk of dataChunks) {
req.emit("data", Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk));
}
if (simulateError) {
req.emit("error", new Error("Simulated stream error"));
} else {
req.emit("end");
}
});

Choose a reason for hiding this comment

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

The use of process.nextTick to emit 'data', 'error', and 'end' events in createMockReq may lead to race conditions if listeners are not attached synchronously before the next tick. This could result in flaky tests if the event loop timing changes or if listeners are attached asynchronously.

Recommended solution:
Consider refactoring the helper to allow explicit control over when events are emitted, or ensure that all listeners are attached before emitting any events. For example, you could return an object with explicit emitData() and emitEnd() methods, or use a promise to synchronize event emission with listener attachment.

@github-actions github-actions bot added the tests label Feb 28, 2026
@gemini-code-assist
Copy link

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request introduces a comprehensive suite of unit tests for the core HTTP helper functions located in src/api/http-helpers.ts. The tests validate critical aspects such as request body parsing, payload size limits, error handling, and JSON response serialization, significantly enhancing the robustness and reliability of these utilities by covering various scenarios and edge cases.

Highlights

  • Comprehensive Unit Testing: Added extensive unit tests for the core HTTP helper functions in src/api/http-helpers.ts.
  • Request Body Parsing Validation: Validated readRequestBodyBuffer, readRequestBody, and readJsonBody functions, covering successful data reading, encoding, and JSON parsing.
  • Payload Limit Enforcement: Tested request body size limits (maxBytes) and associated flag behaviors such as returnNullOnTooLarge and destroyOnTooLarge.
  • Error Handling Verification: Ensured correct error handling for stream errors, malformed JSON, and other request processing issues, including custom error messages and null returns.
  • JSON Response Serialization: Verified writeJsonResponse, writeJsonError, and their 'safe' and 'send' variants for correct JSON serialization, header setting, and status code management.
  • Object Body Identification: Included tests for isJsonObjectBody to correctly identify JSON objects and reject other types.
  • No Production Code Changes: All changes are confined to a new test file, ensuring no modifications to existing production code.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Changelog
  • src/api/http-helpers.test.ts
    • Added new test file for http-helpers.ts.
Activity
  • Pull request was automatically created by Jules for a task initiated by @Dexploarer.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request adds a comprehensive suite of unit tests for the http-helpers.ts module. The tests are well-structured and cover a wide range of scenarios, including stream behavior, payload limits, error handling, and various flag combinations. I've identified a couple of opportunities to enhance test coverage for specific error and edge cases. Overall, this is a great addition that significantly improves the robustness of the HTTP helper functions.


expect(() => writeJsonResponseSafe(res, { a: 1 })).not.toThrow();
});

Choose a reason for hiding this comment

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

medium

While writeJsonResponseSafe has a test to ensure it doesn't throw on response write errors, the equivalent function writeJsonErrorSafe is missing a similar test. Adding this test would improve coverage for error handling paths.

Suggested change
it("writeJsonErrorSafe should not throw on response write errors", async () => {
const { res } = createMockRes();
res.end = vi.fn(() => { throw new Error("Connection closed"); });
expect(() => writeJsonErrorSafe(res, "Oops")).not.toThrow();
});

Comment on lines +198 to +206
it("should reject non-object JSON if requireObject is true", async () => {
const req = createMockReq(['[1, 2, 3]']);
const { res, getJsonOutput } = createMockRes();

const parsed = await readJsonBody(req, res);
expect(parsed).toBeNull();
expect(res.statusCode).toBe(400);
expect(getJsonOutput()).toBe(JSON.stringify({ error: "Request body must be a JSON object" }));
});

Choose a reason for hiding this comment

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

medium

This test only covers arrays. To make it more comprehensive, you could parameterize it to also test for other non-object JSON types like null, which is a valid JSON value. Using it.each from vitest would be a clean way to cover multiple cases.

    it.each([
      ['array', '[1, 2, 3]'],
      ['null', 'null'],
    ])('should reject non-object JSON (%s) if requireObject is true', async (_type, json) => {
      const req = createMockReq([json]);
      const { res, getJsonOutput } = createMockRes();

      const parsed = await readJsonBody(req, res);
      expect(parsed).toBeNull();
      expect(res.statusCode).toBe(400);
      expect(getJsonOutput()).toBe(JSON.stringify({ error: "Request body must be a JSON object" }));
    });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant