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

chore: improve jest #5729

Merged
merged 2 commits into from
Oct 29, 2024
Merged

chore: improve jest #5729

merged 2 commits into from
Oct 29, 2024

Conversation

Dogtiti
Copy link
Member

@Dogtiti Dogtiti commented Oct 28, 2024

💻 变更类型 | Change Type

  • feat
  • fix
  • refactor
  • perf
  • style
  • test
  • docs
  • ci
  • chore
  • build

🔀 变更说明 | Description of Change

📝 补充信息 | Additional Information

Summary by CodeRabbit

  • New Features

    • Introduced a mock implementation of the global fetch function for testing, allowing simulation of network requests without actual HTTP calls.
    • Added @testing-library/dom to enhance testing capabilities.
  • Chores

    • Updated package.json by removing and re-adding the mermaid dependency, ensuring correct versioning.

Copy link

vercel bot commented Oct 28, 2024

@Dogtiti is attempting to deploy a commit to the NextChat Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Contributor

coderabbitai bot commented Oct 28, 2024

Walkthrough

The changes in this pull request introduce a mock implementation of the global fetch function in the jest.setup.ts file for testing purposes. This mock simulates network requests by returning a resolved promise with a predefined response structure. Additionally, the package.json file has been modified to include a new dependency, @testing-library/dom, and the mermaid dependency was removed and re-added, indicating a change in its versioning.

Changes

File Change Summary
jest.setup.ts Added a mock implementation of the global fetch function using jest.fn().
package.json - Added dependency: "@testing-library/dom": "^10.4.0" in devDependencies
- Removed and re-added dependency: "mermaid": "^10.6.1" in dependencies

Possibly related PRs

  • feat: jest #5211: Introduces a jest.setup.ts file that enhances Jest testing capabilities, related to the mock implementation of fetch.

Suggested reviewers

  • lloydzhou

Poem

🐇 In the land of tests, where bunnies play,
A mock fetch hops in, to save the day.
With promises bright, it fetches with glee,
Testing made easy, oh what joy to see!
Dependencies dance, with @testing-library in tow,
Let's celebrate changes, and watch our tests grow! 🎉


📜 Recent review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 49d42bb and 89cea18.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (1)
  • package.json (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • package.json

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

@Dogtiti
Copy link
Member Author

Dogtiti commented Oct 28, 2024

用于修复单元测试引用方法函数会涉及到fetch而报错的问题

@Issues-translate-bot
Copy link

Bot detected the issue body's language is not English, translate it automatically.


Used to fix the problem of unit test reference method functions involving fetch and reporting errors.

Copy link
Contributor

Your build has completed!

Preview deployment

Copy link
Contributor

@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 and nitpick comments (1)
jest.setup.ts (1)

4-24: Consider a more flexible mocking strategy.

While global mocks are convenient, they can make tests harder to maintain and understand. Consider these architectural improvements:

  1. Create a separate mock configuration file to manage different response scenarios
  2. Use dependency injection in your code instead of relying on global fetch
  3. Consider using MSW (Mock Service Worker) for more realistic API mocking

Would you like me to provide examples of these alternative approaches?

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 4f49626 and 49d42bb.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (2)
  • jest.setup.ts (1 hunks)
  • package.json (2 hunks)
🔇 Additional comments (4)
jest.setup.ts (2)

1-2: LGTM! Good documentation reference.

The import statement is correct and the comment helpfully links to the documentation.


4-24: ⚠️ Potential issue

Enhance fetch mock implementation for better test coverage.

The current fetch mock implementation has several areas for improvement:

  1. The mock is oversimplified and always returns empty values, which might lead to false-positive test results
  2. The clone() implementation is incorrect as it returns the same instance
  3. No error scenarios are handled
  4. Response body handling is too generic

Consider implementing a more robust mock:

-global.fetch = jest.fn(() =>
-  Promise.resolve({
-    ok: true,
-    status: 200,
-    json: () => Promise.resolve({}),
-    headers: new Headers(),
-    redirected: false,
-    statusText: "OK",
-    type: "basic",
-    url: "",
-    clone: function () {
-      return this;
-    },
-    body: null,
-    bodyUsed: false,
-    arrayBuffer: () => Promise.resolve(new ArrayBuffer(0)),
-    blob: () => Promise.resolve(new Blob()),
-    formData: () => Promise.resolve(new FormData()),
-    text: () => Promise.resolve(""),
-  }),
-);
+global.fetch = jest.fn((input: RequestInfo | URL, init?: RequestInit) => {
+  // Store response data for reuse in cloned responses
+  const responseData = {
+    body: JSON.stringify({ message: "Default response" }),
+    init: {
+      status: 200,
+      statusText: "OK",
+      headers: new Headers(init?.headers),
+    },
+  };
+
+  // Create response object factory to ensure each response is unique
+  const createResponse = (data: typeof responseData) => {
+    let bodyUsed = false;
+    const response = new Response(data.body, data.init);
+
+    return {
+      ...response,
+      // Override clone to create a new response with the same data
+      clone: () => createResponse(data),
+      // Implement proper body usage tracking
+      get bodyUsed() {
+        return bodyUsed;
+      },
+      json: async () => {
+        bodyUsed = true;
+        return JSON.parse(data.body);
+      },
+      text: async () => {
+        bodyUsed = true;
+        return data.body;
+      },
+    };
+  };
+
+  return Promise.resolve(createResponse(responseData));
+});

This implementation:

  • Creates unique response objects for each request
  • Properly implements clone()
  • Tracks body usage
  • Provides actual response data
  • Can be extended to handle different URLs and methods

You might also want to add helper methods to simulate different scenarios:

// Add these helper methods to configure the mock for different scenarios
export const mockFetchResponse = (data: any, status = 200) => {
  (global.fetch as jest.Mock).mockImplementationOnce(() =>
    Promise.resolve({
      ok: status >= 200 && status < 300,
      status,
      json: () => Promise.resolve(data),
      // ... other response properties
    }),
  );
};

export const mockFetchError = (error: Error) => {
  (global.fetch as jest.Mock).mockImplementationOnce(() =>
    Promise.reject(error),
  );
};

Let's verify if there are any existing tests that might break with this change:

package.json (2)

59-59: LGTM! Good addition for DOM testing capabilities.

Adding @testing-library/dom is a good choice as it complements the existing testing setup with @testing-library/react and @testing-library/jest-dom. This will provide more granular DOM testing capabilities, which aligns well with the PR's objective to improve Jest testing.


37-37: Verify if mermaid dependency change was intentional.

The mermaid dependency appears to have been removed and re-added with the same version. Given this PR's focus on Jest improvements, please confirm if this change was intentional.

@Dogtiti Dogtiti merged commit 613d67e into ChatGPTNextWeb:main Oct 29, 2024
1 check failed
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