-
Notifications
You must be signed in to change notification settings - Fork 59.7k
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
chore: improve jest #5729
Conversation
@Dogtiti is attempting to deploy a commit to the NextChat Team on Vercel. A member of the Team first needs to authorize it. |
WalkthroughThe changes in this pull request introduce a mock implementation of the global Changes
Possibly related PRs
Suggested reviewers
Poem
📜 Recent review detailsConfiguration used: CodeRabbit UI ⛔ Files ignored due to path filters (1)
📒 Files selected for processing (1)
🚧 Files skipped from review as they are similar to previous changes (1)
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? 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
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)
Other keywords and placeholders
CodeRabbit Configuration File (
|
用于修复单元测试引用方法函数会涉及到fetch而报错的问题 |
Used to fix the problem of unit test reference method functions involving fetch and reporting errors. |
Your build has completed! |
There was a problem hiding this 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:
- Create a separate mock configuration file to manage different response scenarios
- Use dependency injection in your code instead of relying on global fetch
- 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
⛔ 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 issueEnhance fetch mock implementation for better test coverage.
The current fetch mock implementation has several areas for improvement:
- The mock is oversimplified and always returns empty values, which might lead to false-positive test results
- The
clone()
implementation is incorrect as it returns the same instance- No error scenarios are handled
- 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.
…into feature/jest
💻 变更类型 | Change Type
🔀 变更说明 | Description of Change
📝 补充信息 | Additional Information
Summary by CodeRabbit
New Features
fetch
function for testing, allowing simulation of network requests without actual HTTP calls.@testing-library/dom
to enhance testing capabilities.Chores
package.json
by removing and re-adding themermaid
dependency, ensuring correct versioning.