Skip to content

Conversation

@justin808
Copy link
Member

@justin808 justin808 commented Nov 21, 2025

Summary

Addresses #844 by adding comprehensive Jest unit tests for the rspack public API exports in package/rspack/index.ts.

What was tested

All 17 tests pass and verify:

Webpack-merge function exports - merge, mergeWithRules, mergeWithCustomize, unique
Configuration object exports - config, devServer, env, rules, baseConfig
Utility function exports - moduleExists, canProcess, inliningCss
generateRspackConfig() behavior:

  • Returns immutable config objects
  • Properly merges extra configuration
  • Validates input arguments (errors on multiple configs)
  • Includes required plugins array
  • Includes optimization object
  • Includes module rules array
  • Respects NODE_ENV for environment-specific configs
  • Falls back to base config for unknown environments
  • Correctly merges environment and extra configs

Key improvements

  • baseConfig verification: Tests confirm baseConfig is a valid rspack configuration object with required properties (output, resolve), helping catch issues like those reported in baseConfig export from rspack is broken, baseConfig for webpack might be broken as well #843
  • Dependency validation mocking: Tests mock validateRspackDependencies() to avoid requiring actual rspack dependencies during test runs
  • Environment variable setup: Tests properly set SHAKAPACKER_ASSETS_BUNDLER=rspack to ensure rspack-specific code paths are tested

Test file location

test/package/rspack/index.test.js - mirrors the structure of existing test/package/index.test.js for webpack

Test plan

  • All 17 new tests pass
  • All existing package tests still pass
  • Linting passes

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Tests
    • Added comprehensive rspack integration tests validating the public API surface.
    • Verifies configuration generation is immutable, supports merging additional settings, and rejects multiple-config input.
    • Confirms generated configs include plugins, optimization, and module rules.
    • Checks environment-specific behavior (e.g., production mode) and fallback to base configuration when env-specific settings are missing.

@coderabbitai
Copy link

coderabbitai bot commented Nov 21, 2025

Walkthrough

Adds a new test suite at test/package/rspack/index.test.js that exercises the public API of the rspack index integration, including exported utilities and generateRspackConfig, and verifies config immutability, merging behavior, error cases, plugin/module inclusion, and NODE_ENV-driven mode selection.

Changes

Cohort / File(s) Summary
Rspack Index Integration Tests
test/package/rspack/index.test.js
Adds a ~190-line test suite that mocks dependency utilities, initializes a test app environment for the rspack bundler, and verifies exported API surfaces (merge*, unique, config, devServer, env, baseConfig, moduleExists, canProcess, inliningCss, generateRspackConfig). Tests cover immutability, merging extra config, error on multiple configs, inclusion of plugins/optimization/rules, NODE_ENV-driven production mode, and environment config fallback/merging.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐰
A tiny test hopped in to play,
Checking configs both night and day,
Mocks and asserts all in a line,
Rspack’s export garden looks fine,
I nibble bugs and leave green signs. 🥕

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main change: adding comprehensive unit tests for rspack exports.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch jg-/beirut-v2

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@claude
Copy link

claude bot commented Nov 21, 2025

Pull Request Review

Summary

This PR adds comprehensive Jest unit tests for the rspack public API exports, addressing issue #844. Overall, this is a high-quality contribution that significantly improves test coverage for the rspack functionality.

✅ Strengths

  1. Excellent test coverage: 17 tests cover all major exports and edge cases
  2. Good structure: Mirrors the existing test/package/index.test.js pattern for consistency
  3. Proper mocking: Correctly mocks validateRspackDependencies() and moduleExists() to avoid dependency requirements
  4. Environment setup: Properly sets SHAKAPACKER_ASSETS_BUNDLER=rspack for rspack-specific code paths
  5. Thorough edge cases: Tests immutability, config merging, error conditions, and fallback behavior

🔍 Code Quality Observations

Minor Issues

  1. Missing trailing newline ⚠️

    • Line 190 of test/package/rspack/index.test.js is missing a trailing newline
    • This will fail the project's linting rules per CLAUDE.md
    • Action required: Add a newline at the end of the file
  2. Path inconsistency in mocks

    • The webpack test (test/package/index.test.js) uses require("../../package/utils/helpers")
    • The rspack test uses require("../../../package/utils/helpers")
    • Both are correct for their respective locations, but worth noting the directory structure difference
  3. Test description consistency

    • Line 19: "webpackConfig returns an immutable object" (in webpack tests)
    • Line 88: "generateRspackConfig returns an immutable object" (in rspack tests)
    • The rspack version is more precise. Consider updating the webpack test for consistency (separate PR)

🧪 Test Coverage Analysis

All critical functionality is tested:

  • ✅ Webpack-merge function exports (merge, mergeWithRules, etc.)
  • ✅ Configuration objects (config, devServer, env, rules, baseConfig)
  • ✅ Utility functions (moduleExists, canProcess, inliningCss)
  • ✅ generateRspackConfig behavior (immutability, merging, validation, plugins, optimization, module rules)
  • ✅ Environment-specific configs (NODE_ENV handling)
  • ✅ Error conditions (multiple configs error)
  • ✅ Fallback behavior (unknown environments)

Test Coverage vs Source Code

Comparing with package/rspack/index.ts:

  • ✅ All exports are tested
  • ✅ The validateRspackDependencies() call is properly mocked (line 30 in source)
  • ✅ Environment config loading logic is tested (lines 37-40 in source)
  • ✅ Config merging is tested (line 52 in source)

🔒 Security Considerations

No security concerns identified. The tests:

  • Don't execute arbitrary code
  • Properly mock external dependencies
  • Use safe file system operations via the test helper

⚡ Performance Considerations

  • Tests use jest.resetModules() before each test, which is necessary but can be slow
  • This is consistent with existing test patterns in the codebase
  • No performance issues expected

📝 Best Practices

  1. ✅ Follows existing test patterns
  2. ✅ Proper setup/teardown with beforeEach and afterAll
  3. ✅ Clear, descriptive test names
  4. ✅ Tests one concern per test case
  5. ✅ Good use of Jest matchers

🐛 Potential Issues

Low Priority

  1. resetEnv() behavior (line 54 in helpers.js)
    • process.env = {} completely wipes the environment, which could break Node.js internals
    • However, this is existing code, not introduced by this PR
    • Consider filing a separate issue if this causes problems

📋 Action Items

Required before merge:

  • Add trailing newline at end of file (line 190)
  • Run yarn lint to verify no linting errors
  • Verify all tests pass with yarn test test/package/rspack/index.test.js

Optional improvements (could be follow-up PRs):

  • Consider adding tests for the re-exported webpack-merge functions (they're tested indirectly but not explicitly)
  • Add tests for edge cases like passing undefined or null to generateRspackConfig

✅ Recommendation

APPROVE with minor fix required: This is an excellent addition to the test suite. Once the trailing newline is added, this should be merged.

The tests are well-structured, comprehensive, and directly address the issues mentioned in #844 and help prevent regressions of #843.


🤖 Generated with Claude Code

@claude
Copy link

claude bot commented Nov 21, 2025

Code Review - PR #847: Add comprehensive unit tests for rspack exports

Thank you for this excellent contribution! The test coverage for the rspack public API is much needed and well-implemented. Here's my detailed feedback:

✅ Strengths

  1. Comprehensive Coverage: All 17 exports from package/rspack/index.ts are properly tested, including:

    • webpack-merge functions (merge, mergeWithRules, mergeWithCustomize, unique)
    • Configuration objects (config, devServer, env, rules, baseConfig)
    • Utility functions (moduleExists, canProcess, inliningCss)
    • The main generateRspackConfig() function
  2. Good Test Structure: The tests mirror the existing webpack tests in test/package/index.test.js, maintaining consistency across the codebase.

  3. Proper Mocking: The mocks for moduleExists and validateRspackDependencies are well-designed to isolate the tests from external dependencies.

  4. Environment Testing: Tests verify environment-specific behavior (development vs production) and fallback to base config for unknown environments.

  5. Immutability Verification: Good testing of the immutability guarantee that generateRspackConfig() provides.

🔍 Issues & Concerns

1. Missing Trailing Newline ⚠️

Per the project's CLAUDE.md guidelines, all files must end with a trailing newline. The test file appears to be missing this at line 190.

Fix: Add a newline after the final closing brace.

2. Inconsistent Error Message Testing

Line 118 tests for error message:

"use webpack-merge to merge configs before passing them to Shakapacker"

However, the actual error message in package/rspack/index.ts:33-34 is:

"Only one extra config may be passed here - use webpack-merge to merge configs before passing them to Shakapacker"

The test only checks for a substring match, which works but could be more precise. The webpack version at package/index.ts:30-40 has a much more helpful multi-line error message with examples.

Suggestion: Either:

  • Update the rspack error message to match the webpack version's verbosity
  • Update the test to check for the full error message, or at least "Only one extra config"

3. Test Name Inconsistency

Line 89: Test is named "generateRspackConfig returns an immutable object" but the webpack equivalent (line 19) is "webpackConfig returns an immutable object".

This is actually better in the rspack version as it's more descriptive. Consider updating the webpack test for consistency.

4. Potential Race Condition with jest.resetModules()

Lines 152 and 176 call jest.resetModules() inside individual tests to test different NODE_ENV values. This is fine for isolated tests but could cause issues if tests run in parallel or if module state leaks between tests.

Suggestion: Consider using beforeEach to reset modules consistently, or document why resetModules is needed only in specific tests.

5. Missing Type Validation

The rspack implementation uses TypeScript (index.ts) but the tests are in JavaScript (.test.js). While this is fine for runtime behavior, it doesn't verify type safety.

Nice-to-have: Consider adding type-level tests or at least JSDoc comments in the test file to verify TypeScript types are exported correctly.

🎯 Code Quality

  • Readability: Excellent - tests are clear and well-organized
  • Maintainability: Good - follows existing patterns
  • Test isolation: Good - proper use of mocks and beforeEach/afterAll
  • Documentation: The PR description is thorough and explains the test coverage well

🔒 Security Concerns

No security issues identified. The tests are read-only and properly mock external dependencies.

⚡ Performance Considerations

  • The test setup calls chdirTestApp() which changes the working directory. The afterAll hook properly restores it.
  • Multiple jest.resetModules() calls could slow down test execution slightly, but this is acceptable for thorough environment testing.

📋 Recommendations

Before merging:

  1. ✅ Add trailing newline to the test file
  2. ⚠️ Consider improving the error message test to be more specific
  3. ✅ Run yarn lint to verify (mentioned in PR but good to confirm)

Future improvements:

  1. Consider harmonizing error messages between webpack and rspack implementations
  2. Add a comment explaining why SHAKAPACKER_ASSETS_BUNDLER=rspack is set in beforeEach
  3. Consider adding a test that verifies the module exports exactly match what's in the TypeScript source

📊 Test Coverage Assessment

This PR successfully addresses issue #844 by providing comprehensive unit tests for the rspack public API. The tests verify both the happy path and error cases, which should help catch issues like the baseConfig problem mentioned in issue #843.

✅ Overall Assessment

This is a high-quality PR that significantly improves the project's test coverage and reliability. With the minor fixes above, this is ready to merge.

Recommendation: Approve with minor changes


🤖 Generated with Claude Code

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: 1

🤖 Fix all issues with AI agents
In @test/package/rspack/index.test.js:
- Around line 89-100: The immutability test for generateRspackConfig is
asserting the wrong value after mutating rspackConfig1.output.path: it sets
rspackConfig1.output.path = "new path" but then checks rspackConfig2.output.path
is not "new value"; update the assertion to check rspackConfig2.output.path is
not "new path" (or change the mutated value to "new value" so assertions match)
so the test actually verifies that modifying rspackConfig1 does not affect
rspackConfig2; locate generateRspackConfig and the rspackConfig1/rspackConfig2
variables in the test and make the assertion consistent.
📜 Review details

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3e06781 and a243a39.

📒 Files selected for processing (1)
  • test/package/rspack/index.test.js
🧰 Additional context used
🧠 Learnings (3)
📓 Common learnings
Learnt from: CR
Repo: shakacode/shakapacker PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-22T04:44:25.430Z
Learning: This gem supports both webpack and rspack configurations - test changes with both bundlers when modifying core functionality
📚 Learning: 2025-12-22T04:44:25.430Z
Learnt from: CR
Repo: shakacode/shakapacker PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-12-22T04:44:25.430Z
Learning: This gem supports both webpack and rspack configurations - test changes with both bundlers when modifying core functionality

Applied to files:

  • test/package/rspack/index.test.js
📚 Learning: 2024-10-09T10:47:17.620Z
Learnt from: marvinthepa
Repo: shakacode/shakapacker PR: 520
File: spec/shakapacker/utils_manager_spec.rb:68-89
Timestamp: 2024-10-09T10:47:17.620Z
Learning: In `spec/shakapacker/utils_manager_spec.rb`, the code within the context `"when lockfile is in Rails.root, but pwd is different"` is not duplicated for each package manager.

Applied to files:

  • test/package/rspack/index.test.js
🧬 Code graph analysis (1)
test/package/rspack/index.test.js (2)
test/helpers.js (2)
  • chdirTestApp (43-49)
  • resetEnv (53-55)
package/rspack/index.ts (1)
  • generateRspackConfig (66-66)
🔇 Additional comments (4)
test/package/rspack/index.test.js (4)

1-26: LGTM! Clean mocking setup.

The mocking strategy appropriately isolates the rspack functionality by:

  • Mocking moduleExists to return false, avoiding external dependency checks
  • Mocking validateRspackDependencies to skip validation during tests

This follows best practices for unit testing by eliminating external dependencies.


27-34: LGTM! Proper test suite setup.

The setup correctly:

  • Resets modules and environment between tests for isolation
  • Sets SHAKAPACKER_ASSETS_BUNDLER=rspack to exercise rspack-specific code paths (as mentioned in PR objectives)
  • Restores the original directory after all tests

35-87: LGTM! Comprehensive export validation.

The tests systematically verify all expected exports from the rspack index module:

  • Webpack-merge functions (merge, mergeWithRules, mergeWithCustomize, unique)
  • Configuration objects (config, devServer, env, rules, baseConfig)
  • Utility functions (moduleExists, canProcess, inliningCss)
  • generateRspackConfig function

The baseConfig validation at lines 73-74 is particularly valuable as it checks for required properties (output, resolve), helping catch regressions like issue #843 mentioned in the PR objectives.


102-189: LGTM! Comprehensive behavior validation.

The remaining tests thoroughly validate generateRspackConfig behavior:

  • Config merging with proper assertions for nested properties (lines 102-115)
  • Error handling for invalid inputs (lines 117-123)
  • Structural requirements: plugins, optimization, and module.rules (lines 125-151)
  • Environment-specific behavior with proper module reloading via jest.resetModules() (lines 153-189)

The tests correctly use jest.resetModules() when changing NODE_ENV to ensure the module is re-imported with the new environment variables, which is essential for accurate testing.

@claude
Copy link

claude bot commented Jan 8, 2026

Code Review - PR #847

I've reviewed the comprehensive unit tests for rspack exports. Overall, this is a solid addition that significantly improves test coverage for the rspack public API. Here's my detailed feedback:


✅ Strengths

1. Excellent Test Coverage

  • All 17 public API exports are tested
  • Comprehensive coverage of generateRspackConfig() behavior including edge cases
  • Tests verify immutability, merging, validation, and environment-specific behavior
  • Good alignment with issue Rspack support needs unit tests #844's requirements

2. Follows Existing Patterns

  • Mirrors the structure of test/package/index.test.js for webpack
  • Uses same test helpers (chdirTestApp, resetEnv)
  • Consistent mocking approach for dependencies
  • Follows project conventions (as per CLAUDE.md)

3. Proper Test Isolation

  • jest.resetModules() ensures clean state between tests
  • resetEnv() clears environment variables
  • Mocking prevents external dependencies from affecting tests
  • Proper cleanup with afterAll() to restore working directory

4. Good Mock Design

  • Mocking validateRspackDependencies() is correct - tests shouldn't require actual rspack installation
  • Mocking moduleExists() to return false prevents side effects
  • Uses jest.requireActual() to preserve original functionality where needed

🔍 Issues & Suggestions

Critical Issue: Missing Trailing Newline

Location: test/package/rspack/index.test.js:190

The file must end with a trailing newline character per the project's linting rules (see CLAUDE.md). This will fail yarn lint.

Fix: Add a blank line at the end of the file.


Minor Issues

1. Inconsistent Assertion in Line 29

Location: test/package/rspack/index.test.js:29

expect(webpackConfig2.output.path).not.toBe("new value") 

Should be "new path" to match the assignment on line 26:

webpackConfig1.output.path = "new path"

This is copying the same typo from test/package/index.test.js:29. While it doesn't break the test (both strings are different from the actual value), it's confusing for maintainability.


2. Test Description Clarity

Location: Multiple tests (lines 34, 49, 61, 67)

Some test descriptions use generic terms:

  • "exports config object" - Consider: "exports shakapacker config object"
  • "exports devServer object" - Consider: "exports dev server configuration"
  • "exports env object" - Consider: "exports environment variables object"

These are minor readability improvements, not critical issues.


3. Environment Test Could Be More Specific

Location: test/package/rspack/index.test.js:151-158

The production mode test verifies the mode is set to "production", but it might be more robust to also check for production-specific optimizations (minification settings, etc.) to ensure the production environment config is actually being used.

Suggestion:

test("generateRspackConfig respects NODE_ENV for environment config", () => {
  process.env.NODE_ENV = "production"
  jest.resetModules()

  const { generateRspackConfig } = require("../../../package/rspack/index")
  const rspackConfig = generateRspackConfig()

  expect(rspackConfig).toHaveProperty("mode", "production")
  // Also verify production-specific config is applied
  expect(rspackConfig.optimization).toBeDefined()
})

4. Missing Test: Actual baseConfig Export Verification

Location: test/package/rspack/index.test.js:67-74

Given that issue #843 specifically mentions baseConfig export is broken, the test should verify that the exported baseConfig is actually usable as a valid rspack configuration, not just that it has output and resolve properties.

Suggestion: Add assertions to verify it contains expected base configuration properties:

test("exports baseConfig object", () => {
  const rspack = require("../../../package/rspack/index")
  expect(rspack.baseConfig).toBeDefined()
  expect(typeof rspack.baseConfig).toBe("object")
  expect(rspack.baseConfig).toHaveProperty("output")
  expect(rspack.baseConfig).toHaveProperty("resolve")
  
  // Verify critical base properties exist
  expect(rspack.baseConfig.output).toHaveProperty("path")
  expect(rspack.baseConfig.output).toHaveProperty("publicPath")
  expect(rspack.baseConfig.resolve).toHaveProperty("extensions")
})

🎯 Performance Considerations

No performance concerns. The tests are lightweight and properly isolated.


🔒 Security Concerns

None. This is test code with no security implications.


📋 Test Recommendations

Before Merging:

  1. Fix the missing trailing newline (critical for lint)
  2. Run yarn lint to verify formatting
  3. Run the full test suite to ensure no regressions

Future Enhancements (Optional):

  1. Consider adding integration tests that verify rspack actually builds with the generated config
  2. Test error cases more thoroughly (e.g., what happens with invalid extra config)
  3. Add tests for specific plugin and optimization configurations

📊 Summary

Recommendation:Approve with minor fixes

This PR successfully addresses issue #844 by providing comprehensive test coverage for the rspack public API. The code quality is high, follows project conventions, and uses appropriate testing patterns.

Required Changes:

  • Add trailing newline at end of file

Suggested Changes:

Great work on the thorough test coverage! This will help catch regressions and ensure the rspack integration remains stable.

@justin808 justin808 added the p1 High: important bugs, approved PRs ready to merge label Feb 9, 2026
Addresses issue #844 by adding Jest unit tests for the rspack public API.
These tests verify all exports from package/rspack/index.ts work correctly.

Tests cover:
- Webpack-merge function exports (merge, mergeWithRules, etc.)
- Configuration object exports (config, devServer, env, rules, baseConfig)
- Utility function exports (moduleExists, canProcess, inliningCss)
- generateRspackConfig() behavior:
  - Returns immutable config objects
  - Properly merges extra configuration
  - Validates input arguments
  - Includes required plugins and optimization
  - Respects NODE_ENV for environment-specific configs
  - Falls back to base config for unknown environments
  - Merges environment and extra configs correctly

The baseConfig export is verified to be a valid rspack configuration
object, which helps catch issues like those reported in #843.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>
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: 1

🤖 Fix all issues with AI agents
In `@test/package/rspack/index.test.js`:
- Line 190: Add a trailing newline at the end of
test/package/rspack/index.test.js by ensuring there's a newline character after
the final closing characters "})" (the end of the test block) so the file ends
with a single newline; simply edit the file and insert a newline at EOF and
save.
🧹 Nitpick comments (1)
test/package/rspack/index.test.js (1)

153-175: Consider asserting more than just mode for the production config, and more than non-throwing for the fallback.

These tests work but are relatively shallow. For the production test (line 160), you might also verify that production-specific settings (e.g., minimizer enabled) are present. For the fallback test (lines 170-174), calling generateRspackConfig() twice (once to assert no-throw, once to capture the result) is redundant — you could capture and assert in one call.

♻️ Minor simplification for the fallback test
-    // Should not throw, should use baseConfig
-    expect(() => generateRspackConfig()).not.toThrow()
-
-    const rspackConfig = generateRspackConfig()
+    // Should not throw, should use baseConfig
+    const rspackConfig = generateRspackConfig()
     expect(rspackConfig).toHaveProperty("output")
     expect(rspackConfig).toHaveProperty("resolve")

expect(rspackConfig).toHaveProperty("devtool", "custom-source-map")
expect(rspackConfig).toHaveProperty("mode", "development")
})
})
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Add a trailing newline at end of file.

The file should end with a trailing newline character. As per coding guidelines, all files must end with a trailing newline.

🤖 Prompt for AI Agents
In `@test/package/rspack/index.test.js` at line 190, Add a trailing newline at the
end of test/package/rspack/index.test.js by ensuring there's a newline character
after the final closing characters "})" (the end of the test block) so the file
ends with a single newline; simply edit the file and insert a newline at EOF and
save.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

p1 High: important bugs, approved PRs ready to merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant