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

feat: jest #5211

Merged
merged 4 commits into from
Oct 10, 2024
Merged

feat: jest #5211

merged 4 commits into from
Oct 10, 2024

Conversation

Dogtiti
Copy link
Member

@Dogtiti Dogtiti commented Aug 6, 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 Jest configuration for seamless testing in Next.js applications, including support for JavaScript and TypeScript files.
    • Added a setup file that enhances Jest with additional matchers for improved DOM testing.
  • Enhancements

    • Added new scripts in the project configuration for improved testing capabilities, including interactive and CI testing.
    • Included essential testing libraries to enhance the development experience and maintain code quality.
    • Enhanced prompt initialization by integrating external data for multiple languages.

@Dogtiti Dogtiti requested a review from lloydzhou August 6, 2024 11:17
Copy link

vercel bot commented Aug 6, 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 Aug 6, 2024

Walkthrough

A comprehensive testing setup has been introduced for a Next.js application, enhancing the development workflow. This includes a Jest configuration file (jest.config.ts), a setup file for custom matchers (jest.setup.ts), and updates to package.json for new testing scripts and dependencies. Additionally, modifications to the onRehydrateStorage method in app/store/prompt.ts allow for the fetching and processing of prompt data from an external JSON file, improving the prompt initialization process.

Changes

Files Change Summary
jest.config.ts, jest.setup.ts, package.json Added Jest configuration for Next.js, including coverage settings, custom matchers, and updated scripts and dependencies for enhanced testing capabilities.
app/store/prompt.ts Modified onRehydrateStorage to fetch prompt data from a JSON file and initialize the SearchService with multilingual prompts.

Possibly related PRs

Suggested reviewers

  • lloydzhou

Poem

In the garden of code, where the rabbits play,
New tests bloom bright, chasing bugs away.
With Jest by our side and matchers in tow,
We hop through the code, watch our features grow!
🐰✨


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.

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 5629f84 and 1ef2aa3.

Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
Files selected for processing (4)
  • jest.config.ts (1 hunks)
  • jest.setup.ts (1 hunks)
  • package.json (1 hunks)
  • test/sum-module.test.ts (1 hunks)
Files skipped from review due to trivial changes (2)
  • jest.setup.ts
  • test/sum-module.test.ts
Additional comments not posted (7)
jest.config.ts (4)

1-2: Imports are appropriate.

The import statements for Config and nextJest are necessary for setting up Jest configuration for a Next.js application.


4-7: Jest configuration creation looks good.

The createJestConfig function is correctly set up to load the Next.js configuration and environment variables from the root directory.


10-18: Custom Jest configuration is comprehensive.

The custom configuration includes:

  • coverageProvider: Set to "v8" for code coverage.
  • testEnvironment: Set to "jsdom" for simulating a browser environment.
  • testMatch: Patterns for matching test files.
  • setupFilesAfterEnv: Specifies the setup file for custom matchers.
  • moduleNameMapper: Maps module paths for easier imports.

These settings are appropriate for testing a Next.js application.


20-21: Jest configuration export is correct.

The Jest configuration is exported using createJestConfig, ensuring that the Next.js configuration is loaded asynchronously.

package.json (3)

19-20: New test scripts are appropriate.

The new scripts for testing are:

  • "test": "jest --watch": For interactive testing.
  • "test:ci": "jest --ci": For continuous integration testing.

These scripts enhance the testing capabilities of the project.


54-75: New devDependencies are essential.

The new devDependencies for testing include:

  • @testing-library/jest-dom
  • @testing-library/react
  • @types/jest
  • jest
  • jest-environment-jsdom
  • ts-node

These dependencies are essential for setting up a comprehensive testing framework for the project.


2-83: Overall changes in package.json enhance testing capabilities.

The changes in package.json include new scripts and devDependencies that significantly enhance the project's testing capabilities, aligning with the goal of introducing Jest and improving the testing framework.

Copy link
Contributor

github-actions bot commented Aug 6, 2024

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

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between 1ef2aa3 and 1287e39.

Files selected for processing (1)
  • package.json (1 hunks)
Files skipped from review as they are similar to previous changes (1)
  • package.json

package.json Show resolved Hide resolved
@Dogtiti Dogtiti requested a review from lloydzhou October 8, 2024 02:32
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 (6)
package.json (1)

19-20: LGTM: Test scripts added for development and CI environments.

The addition of test and test:ci scripts introduces Jest for running tests, which is a great improvement to the project's testing capabilities. The --watch flag for development and --ci flag for CI environments are appropriate choices.

Consider adding a test:coverage script to generate test coverage reports:

  "test": "jest --watch",
  "test:ci": "jest --ci"
+ "test:coverage": "jest --coverage"

This will help track the project's test coverage over time.

app/store/prompt.ts (5)

Line range hint 154-171: Add error handling for the fetch operation

The fetch request lacks error handling. If the network request fails or the response is invalid, it could lead to unhandled promise rejections and runtime errors. Consider adding a .catch() block to handle errors gracefully.

Apply this diff to add error handling:

 fetch(PROMPT_URL)
   .then((res) => res.json())
   .then((res) => {
     // existing code
   })
+  .catch((error) => {
+    console.error('Error fetching prompts:', error);
+    // Optionally, handle the error (e.g., set default prompts or notify the user)
+  });

Line range hint 158-160: Handle potential undefined prompt data

The code assumes that res.en, res.tw, and res.cn exist in the fetched data. If any of these properties are missing or undefined, it could cause runtime errors. Consider providing default empty arrays to ensure robustness.

Apply this diff to provide default values:

 let fetchPrompts = [
-  res.en,
-  res.tw,
-  res.cn
+  res.en || [],
+  res.tw || [],
+  res.cn || []
 ];

Line range hint 165-166: Simplify array flattening using flat()

You can simplify the flattening of builtinPrompts by using the flat() method instead of reduce and concat, improving readability.

Apply this diff to simplify the code:

 const allPromptsForSearch = builtinPrompts
-  .reduce((pre, cur) => pre.concat(cur), [])
+  .flat()
   .filter((v) => !!v.title && !!v.content);

Note: Ensure that the environment supports Array.prototype.flat(), available in ES2019 and later.


Line range hint 159-161: Enhance language handling for future scalability

The current logic reverses fetchPrompts when the language is cn. To support additional languages in the future, consider refactoring this logic to be more dynamic.

For example, you could map language codes to prompt data in an object:

- let fetchPrompts = [res.en, res.tw, res.cn];
- if (getLang() === "cn") {
-   fetchPrompts = fetchPrompts.reverse();
- }
+ const languageOrder = {
+   en: [res.en, res.tw, res.cn],
+   cn: [res.cn, res.tw, res.en],
+ };
+ const currentLang = getLang();
+ let fetchPrompts = languageOrder[currentLang] || [res.en, res.tw, res.cn];

This approach allows for easy extension to other languages and custom ordering.


Line range hint 154-171: Consider using async/await for better readability

Refactoring the promise chain with async/await can improve code readability and simplify error handling. Ensure that onRehydrateStorage supports asynchronous functions before making this change.

If supported, apply this diff:

+ onRehydrateStorage: async (state) => {
    // Existing code
    if (typeof window === "undefined") {
      return;
    }

    const PROMPT_URL = "./prompts.json";

    type PromptList = Array<[string, string]>;

-   fetch(PROMPT_URL)
-     .then((res) => res.json())
-     .then((res) => {
+   try {
+     const response = await fetch(PROMPT_URL);
+     const res = await response.json();

      // existing code within the .then blocks
+   } catch (error) {
+     console.error('Error fetching prompts:', error);
+     // Handle error accordingly
+   }
  },

Note: Verify that onRehydrateStorage can handle asynchronous operations without affecting the store rehydration process.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

📥 Commits

Files that changed from the base of the PR and between 1287e39 and acf9fa3.

⛔ Files ignored due to path filters (1)
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (2)
  • app/store/prompt.ts (1 hunks)
  • package.json (3 hunks)
🧰 Additional context used
🔇 Additional comments (5)
package.json (5)

9-9: LGTM: Running tests before build is a good practice.

Adding yarn test:ci to the build script ensures that tests are run in a CI environment before building the application. This change helps catch potential issues early in the development process.


12-12: LGTM: Consistent approach for running tests before export.

Adding yarn test:ci to the export script maintains consistency with the build script and ensures that tests are run before exporting the application. This change contributes to a more robust development workflow.


15-15: LGTM: Consistent approach for running tests before Tauri app build.

Adding yarn test:ci to the app:build script maintains consistency with the build and export scripts. This ensures that tests are run before building the application using Tauri, contributing to a more robust development process.


Line range hint 1-89: Overall LGTM: Testing setup enhanced, minor verification needed.

The changes to package.json significantly improve the project's testing capabilities by introducing Jest and related dependencies. The modifications to build scripts ensure tests are run before building or exporting the application, which is a good practice for catching issues early.

Regarding the past comment about formatting:

lloydzhou: 这里怎么把package.json完全格式化了???

(Translation: "Why is package.json completely formatted here???")

The current diff doesn't show significant formatting changes. It's possible that the formatting was addressed in a previous commit or that the changes appear more substantial due to the diff representation.

To ensure all changes are intentional, please run the following command and verify that only the expected changes are present:

#!/bin/bash
# Show a condensed diff of package.json
git diff --color-words package.json | grep -v '^\+\+\+\|^---\|^index\|^diff'

This will help confirm that no unintended formatting changes were introduced.


59-61: LGTM: Testing dependencies added, but please verify one version.

The addition of testing-related dependencies (@testing-library/jest-dom, @testing-library/react, @types/jest, jest, jest-environment-jsdom, ts-node) is consistent with the introduction of Jest for testing and enhances the project's testing capabilities.

However, please verify the version of @testing-library/react:

The current version (^16.0.0) seems unusually high and might be incorrect. The latest version as of my last update was in the 13.x range. Please double-check and update if necessary.

Also applies to: 77-78, 81-81

@lloydzhou lloydzhou merged commit ba58018 into ChatGPTNextWeb:main Oct 10, 2024
1 of 2 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Oct 28, 2024
10 tasks
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