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

fix: auto set mocha @eggjs/mock/register on application project type #281

Merged
merged 2 commits into from
Dec 29, 2024

Conversation

fengmk2
Copy link
Member

@fengmk2 fengmk2 commented Dec 29, 2024

Summary by CodeRabbit

  • New Features

    • Added support for automatically registering @eggjs/mock/register in test environments.
    • Introduced ESM (ECMAScript Module) test fixture for enhanced testing capabilities.
    • New default export in the router for handling GET requests with a JSON response.
  • Bug Fixes

    • Refined test file handling for changed files.
    • Updated dependency versions for compatibility.
  • Documentation

    • Added new test cases to verify mock registration in CommonJS and ESM environments.
  • Chores

    • Updated .gitignore to allow tracking specific node_modules directory.
    • Updated package dependencies and peer dependencies.
    • Created a new package.json for the demo app.

Copy link

vercel bot commented Dec 29, 2024

The latest updates on your projects. Learn more about Vercel for Git ↗︎

Name Status Preview Comments Updated (UTC)
egg-bin ✅ Ready (Inspect) Visit Preview 💬 Add feedback Dec 29, 2024 8:54am

Copy link

coderabbitai bot commented Dec 29, 2024

Caution

Review failed

The pull request is closed.

Walkthrough

This pull request introduces changes to the Egg.js testing framework, enhancing the test command functionality and adding support for ECMAScript Module (ESM) environments. Key updates include modifications to the .gitignore file to allow tracking of specific node_modules, updates to dependency versions in package.json, enhancements to the formatMochaArgs method in src/commands/test.ts, and the creation of new test fixtures for both CommonJS and ESM applications. Additionally, new test cases have been added to validate the automatic registration of mock modules.

Changes

File Change Summary
.gitignore Added exclusion rule to allow tracking node_modules in test/fixtures/test-demo-app-esm/
package.json Updated @eggjs/utils to ^4.2.0 and @eggjs/mock to version 6
src/commands/test.ts Enhanced formatMochaArgs method to detect Egg application type and conditionally register @eggjs/mock/register
test/commands/test.test.ts Added two new test cases for auto-requiring @eggjs/mock/register in CommonJS and ESM environments
test/fixtures/test-demo-app-esm/* Created new ESM test fixture with router, config, and test files
test/fixtures/test-demo-app/router.js Removed 'use strict'; directive
test/fixtures/test-demo-app/test/a.test.js Removed await app.ready() call

Sequence Diagram

sequenceDiagram
    participant TestCommand as Test Command
    participant EggUtils as @eggjs/utils
    participant MockRegister as @eggjs/mock/register
    participant TestRunner as Mocha Test Runner

    TestCommand->>EggUtils: Detect Application Type
    EggUtils-->>TestCommand: Return Application Type
    alt Is Application Type
        TestCommand->>MockRegister: Attempt to Register
        MockRegister-->>TestCommand: Registration Result
    end
    TestCommand->>TestRunner: Configure and Run Tests
Loading

Poem

🐰 In the realm of Egg.js, where tests take flight,
Modules dance, both CommonJS and ESM bright
Mock registers with a magical touch
Simplifying tests, we've learned so much!
Code hops forward, with grace and might 🚀


📜 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 3812754 and ba6a27d.

📒 Files selected for processing (1)
  • test/commands/test.test.ts (1 hunks)

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.

Copy link

socket-security bot commented Dec 29, 2024

New and removed dependencies detected. Learn more about Socket for GitHub ↗︎

Package New capabilities Transitives Size Publisher
npm/@eggjs/[email protected] Transitive: environment, eval, filesystem, network, unsafe +65 3.76 MB akitasummer, atian25, coolme200, ...10 more
npm/[email protected] None 0 22.7 MB typescript-bot

🚮 Removed packages: npm/@eggjs/[email protected]

View full report↗︎

Copy link

pkg-pr-new bot commented Dec 29, 2024

Open in Stackblitz

npm i https://pkg.pr.new/eggjs/bin/@eggjs/bin@281

commit: ba6a27d

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

🧹 Nitpick comments (2)
src/commands/test.ts (1)

118-130: Consider providing a gentle warning for missing @eggjs/mock
This logic properly handles the scenario where @eggjs/mock/register may not be installed. However, ignoring the exception silently might confuse end users expecting mock features to be automatically available. Consider logging a user-friendly info or warning when an installation is missing.

test/fixtures/test-demo-app-esm/test/a.test.js (1)

1-10: Clear and concise test coverage
This test effectively verifies the main route’s output. Consider adding negative or edge-case tests for broader coverage.

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 87b2aae and 3812754.

⛔ Files ignored due to path filters (1)
  • test/fixtures/test-demo-app-esm/node_modules/egg is excluded by !**/node_modules/**
📒 Files selected for processing (10)
  • .gitignore (1 hunks)
  • package.json (3 hunks)
  • src/commands/test.ts (2 hunks)
  • test/commands/test.test.ts (1 hunks)
  • test/fixtures/test-demo-app-esm/app/router.js (1 hunks)
  • test/fixtures/test-demo-app-esm/config/config.default.js (1 hunks)
  • test/fixtures/test-demo-app-esm/package.json (1 hunks)
  • test/fixtures/test-demo-app-esm/test/a.test.js (1 hunks)
  • test/fixtures/test-demo-app/app/router.js (0 hunks)
  • test/fixtures/test-demo-app/test/a.test.js (0 hunks)
💤 Files with no reviewable changes (2)
  • test/fixtures/test-demo-app/app/router.js
  • test/fixtures/test-demo-app/test/a.test.js
✅ Files skipped from review due to trivial changes (2)
  • test/fixtures/test-demo-app-esm/config/config.default.js
  • test/fixtures/test-demo-app-esm/package.json
🔇 Additional comments (8)
src/commands/test.ts (1)

7-7: Neat import for advanced Egg detection
Bringing in importResolve, detectType, and EggType from @eggjs/utils is a clean approach to manage application type detection and module resolution.

test/fixtures/test-demo-app-esm/app/router.js (1)

1-8: Simple and effective route definition
The implementation is straightforward. Setting this.body in an async function is consistent with Koa-like contexts. Looks good!

test/commands/test.test.ts (2)

23-32: Solid test for automatic mock registration in CommonJS
The test properly verifies that @eggjs/mock/register is auto-required when running in CommonJS mode and checks for expected output. Great job!


34-43: Robust test for ESM auto-require flow
Similar to the CommonJS test, this ensures the ESM flow automatically loads @eggjs/mock/register. Perfect addition for coverage.

.gitignore (1)

21-21: Allowing ESM fixture dependencies
Excluding node_modules everywhere except for test-demo-app-esm is a practical choice for maintaining a self-contained test fixture.

package.json (3)

21-21: LGTM: Utils dependency upgrade supports new functionality.

The upgrade of @eggjs/utils to ^4.2.0 aligns with the new functionality that uses detectType and EggType imports.


Line range hint 40-44: Good: Optional peer dependency configuration.

Making @eggjs/mock an optional peer dependency is a good practice as it allows flexibility in test configurations while still maintaining compatibility when the package is needed.


38-38: Verify the stability of @eggjs/mock v6.

The change from beta to v6 for @eggjs/mock is a significant upgrade. Since this package is critical for the auto-registration feature, let's verify its stability.

Also applies to: 47-47

✅ Verification successful

@eggjs/mock v6 appears stable and actively maintained

The package shows positive stability indicators:

  • Latest release (v6.0.2) was published recently on December 29, 2024
  • The release contains a minor bug fix for bootstrap app global setting
  • Only one open issue exists, related to TypeScript type definitions
  • The package has reached a stable v6 version number, moving past beta
🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Check the stability and compatibility of @eggjs/mock v6

# Check the package's publish date and release notes
gh api graphql -f query='
{
  repository(owner: "eggjs", name: "mock") {
    releases(first: 1, orderBy: {field: CREATED_AT, direction: DESC}) {
      nodes {
        tagName
        publishedAt
        description
      }
    }
  }
}'

# Check for any recent issues or bug reports
gh api graphql -f query='
{
  repository(owner: "eggjs", name: "mock") {
    issues(first: 5, states: OPEN, orderBy: {field: CREATED_AT, direction: DESC}) {
      nodes {
        title
        createdAt
        labels(first: 5) {
          nodes {
            name
          }
        }
      }
    }
  }
}'

Length of output: 1239

Copy link

codecov bot commented Dec 29, 2024

Codecov Report

Attention: Patch coverage is 71.42857% with 4 lines in your changes missing coverage. Please review.

Project coverage is 95.44%. Comparing base (7078748) to head (ba6a27d).
Report is 3 commits behind head on master.

Files with missing lines Patch % Lines
src/commands/test.ts 71.42% 4 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##           master     #281      +/-   ##
==========================================
- Coverage   95.80%   95.44%   -0.37%     
==========================================
  Files          21       21              
  Lines        1050     1054       +4     
  Branches      174      176       +2     
==========================================
  Hits         1006     1006              
- Misses         44       48       +4     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

@fengmk2 fengmk2 merged commit 929c0f8 into master Dec 29, 2024
19 checks passed
@fengmk2 fengmk2 deleted the mocha-registry branch December 29, 2024 08:55
fengmk2 pushed a commit that referenced this pull request Dec 29, 2024
[skip ci]

## [7.0.1](v7.0.0...v7.0.1) (2024-12-29)

### Bug Fixes

* auto set mocha @eggjs/mock/register on application project type ([#281](#281)) ([929c0f8](929c0f8))
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