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

test(utils): Add unit tests for HTTP utilities. #177

Open
wants to merge 9 commits into
base: main
Choose a base branch
from

Conversation

junhaoliao
Copy link
Member

@junhaoliao junhaoliao commented Feb 7, 2025

Description

  1. Add unit tests for HTTP utilities.
  2. Enforce 100% coverage on src/utils/http.ts.

Checklist

  • The PR satisfies the contribution guidelines.
  • This is a breaking change and that has been indicated in the PR title, OR this isn't a
    breaking change.
  • Necessary docs have been updated, OR no docs need to be updated.

Validation performed

  1. Ran npm run test and observed all tests succeeded, and there was no coverage violation.

Summary by CodeRabbit

  • New Features

    • Introduced an enhanced error conversion method for HTTP requests.
  • Chores

    • Updated development dependencies to maintain toolchain stability.
  • Tests

    • Added unit tests to validate HTTP utility functions and error handling.
    • Improved test coverage criteria for HTTP utility functions.

Copy link

coderabbitai bot commented Feb 7, 2025

Walkthrough

This pull request introduces a strict coverage threshold for src/utils/http.ts in the Jest configuration, updates the development dependencies in package.json by re-adding some plugins and adding a new dependency, and adjusts the src/utils/http.ts exports by exposing the convertAxiosError function. Additionally, new unit tests in test/utils/http.test.ts verify the functionality of both getUint8ArrayFrom and convertAxiosError, ensuring proper error handling and response processing.

Changes

File(s) Change Summary
jest.config.ts, src/utils/http.ts,
test/utils/http.test.ts
- Added a 100% coverage threshold for src/utils/http.ts in Jest.
- Modified export in src/utils/http.ts to include convertAxiosError alongside getUint8ArrayFrom.
- Introduced unit tests covering both functions including error handling scenarios.
package.json - Removed then re-added html-webpack-plugin and mini-css-extract-plugin (indicating a potential update/reinstallation).
- Added a new dependency: "http-status-codes": "^2.3.0".

Sequence Diagram(s)

sequenceDiagram
    participant Test as Unit Test
    participant HttpUtils as HTTP Utility Module
    participant Axios as Axios Library

    Test->>HttpUtils: Call getUint8ArrayFrom (valid source)
    HttpUtils->>Test: Return Uint8Array

    Test->>HttpUtils: Call getUint8ArrayFrom (invalid source)
    HttpUtils->>Test: Throw custom error or TypeError

    Test->>HttpUtils: Call convertAxiosError with Axios error
    HttpUtils->>Test: Return standardized error object
Loading

Possibly related PRs


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 93c89fd and a579f36.

📒 Files selected for processing (1)
  • test/utils/http.test.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • test/utils/http.test.ts

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@junhaoliao
Copy link
Member Author

This PR depends on #176

@junhaoliao junhaoliao marked this pull request as ready for review February 12, 2025 17:50
@junhaoliao junhaoliao changed the title test(http-utils): Add unit tests for HTTP utilities. test(utils): Add unit tests for HTTP utilities. Feb 12, 2025
Copy link

@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.

Actionable comments posted: 0

🔭 Outside diff range comments (1)
src/utils/http.ts (1)

20-22: 🛠️ Refactor suggestion

Follow coding guidelines for boolean expressions

As per coding guidelines, prefer false == <expression> rather than !<expression> or 0 === <expression>.

-        0 === message.length ?
+        false == message.length ?
🧹 Nitpick comments (3)
src/utils/http.ts (1)

15-17: Consider using template literals for better readability

The string concatenation could be more readable using template literals.

-    const details = "undefined" === typeof response ?
-        `${method} ${url} failed with no response: ${code}` :
-        `${method} returned ${response.status}(${response.statusText}): ${response.data as string}`;
+    const details = "undefined" === typeof response
+        ? `${method} ${url} failed with no response: ${code}`
+        : `${method} returned ${response.status}(${response.statusText}): ${response.data as string}`;
test/utils/http.test.ts (2)

13-13: Consider using environment variable for endpoint

The HTTP_BIN_ENDPOINT_BASE should be configurable via environment variables to support different testing environments.

-const HTTP_BIN_ENDPOINT_BASE = "https://cloud.yscope.com/httpbin";
+const HTTP_BIN_ENDPOINT_BASE = process.env.HTTP_BIN_ENDPOINT_BASE ?? "https://cloud.yscope.com/httpbin";

60-71: Improve error handling test pattern

The try-catch pattern could be replaced with Jest's expect.rejects for better test readability.

-        try {
-            // Access a 404 route.
-            await axios.get(url);
-        } catch (e) {
-            const error = convertAxiosError(e as AxiosError);
-            expect(error.cause).toEqual({
-                url: url,
-                code: expectedCode,
-                details: `get returned ${expectedStatus}(${expectedStatusText}): ${expectedBody}`,
-            });
-        }
+        await expect(axios.get(url)).rejects.toThrow();
+        const error = convertAxiosError(await axios.get(url).catch(e => e));
+        expect(error.cause).toEqual({
+            url: url,
+            code: expectedCode,
+            details: `get returned ${expectedStatus}(${expectedStatusText}): ${expectedBody}`,
+        });
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 10b7cf5 and 93c89fd.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (4)
  • jest.config.ts (1 hunks)
  • package.json (1 hunks)
  • src/utils/http.ts (1 hunks)
  • test/utils/http.test.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • package.json
🧰 Additional context used
📓 Path-based instructions (1)
`**/*.{cpp,hpp,java,js,jsx,ts,tsx}`: - Prefer `false ==

**/*.{cpp,hpp,java,js,jsx,ts,tsx}: - Prefer false == <expression> rather than !<expression>.

  • src/utils/http.ts
  • jest.config.ts
  • test/utils/http.test.ts
🔇 Additional comments (4)
src/utils/http.ts (1)

61-64: LGTM! Export statement is properly organized

The export statement is well-structured and follows alphabetical ordering.

jest.config.ts (1)

40-44: LGTM! Coverage threshold aligns with other utilities

The coverage threshold for src/utils/http.ts is appropriately set to 100% for branches, functions, and lines, matching the requirements for other utility files.

test/utils/http.test.ts (2)

15-27: Add more test cases for getUint8ArrayFrom

The current test suite only covers the happy path. Consider adding tests for:

  • Large files
  • Different content types
  • Network timeouts

90-101: LGTM! Thorough error handling test

The test case for missing properties is well-designed and covers important edge cases.

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.

1 participant