Skip to content

test: add comprehensive test suite in conditionalGeneration.js#2030

Open
shivansh-source wants to merge 2 commits intoasyncapi:masterfrom
shivansh-source:shivansh#123
Open

test: add comprehensive test suite in conditionalGeneration.js#2030
shivansh-source wants to merge 2 commits intoasyncapi:masterfrom
shivansh-source:shivansh#123

Conversation

@shivansh-source
Copy link
Copy Markdown

@shivansh-source shivansh-source commented Mar 25, 2026

description : This PR adds a dedicated test suite for lib/conditionalGeneration.js. Despite being a critical component for conditional file and folder generation, this module previously had 0% test coverage. These tests ensure the complex logic for evaluating template configurations remains stable and predictable.
The newly implemented tests provide thorough validation across four primary areas. First, it ensures proper guard clauses by verifying that the utility returns undefined when no configuration is present. For parameter-based generation, the suite covers pass/fail scenarios, missing validation fields, and the correct forwarding of values. For subject-based generation, the tests validate JMESPath resolution, the merging of templateParams.server into the evaluation context, and the performance-critical requirement that asyncapiDocument.json() is only invoked on subject paths. Finally, the suite includes specific coverage for the deprecated conditionalFiles configuration, confirming it triggers the appropriate warning logs and correctly takes precedence over conditionalGeneration during this transition period. This foundational coverage is essential for mitigating regression risks and improving maintainability as we move toward the refactor planned in issue #1553.
fixes #1970

Summary by CodeRabbit

  • Tests
    • Added a comprehensive test suite for conditional generation logic. Covers parameter- and document-driven condition evaluation, handling of missing/undefined validators, logging behaviors for true/false outcomes, server-aware resolution and merging, deprecated conditional-path support and precedence, and multiple edge cases to ensure consistent generation decisions and stronger reliability.

Signed-off-by: shivansh-source <shivanshsiddhi1234@gmail.com>
@changeset-bot
Copy link
Copy Markdown

changeset-bot bot commented Mar 25, 2026

⚠️ No Changeset found

Latest commit: 7eceb3c

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@asyncapi-bot
Copy link
Copy Markdown
Contributor

What reviewer looks at during PR review

The following are ideal points maintainers look for during review. Reviewing these points yourself beforehand can help streamline the review process and reduce time to merge.

  1. PR Title: Use a concise title that follows our Conventional Commits guidelines and clearly summarizes the change using imperative mood (it means spoken or written as if giving a command or instruction, like "add new helper for listing operations")

    Note - In Generator, prepend feat: or fix: in PR title only when PATCH/MINOR release must be triggered.

  2. PR Description: Clearly explain the issue being solved, summarize the changes made, and mention the related issue.

    Note - In Generator, we use Maintainers Work board to track progress. Ensure the PR Description includes Resolves #<issue-number> or Fixes #<issue-number> this will automatically close the linked issue when the PR is merged and helps automate the maintainers workflow.

  3. Documentation: Update the relevant Generator documentation to accurately reflect the changes introduced in the PR, ensuring users and contributors have up-to-date guidance.

  4. Comments and JSDoc: Write clear and consistent JSDoc comments for functions, including parameter types, return values, and error conditions, so others can easily understand and use the code.

  5. DRY Code: Ensure the code follows the Don't Repeat Yourself principle. Look out for duplicate logic that can be reused.

  6. Test Coverage: Ensure the new code is well-tested with meaningful test cases that pass consistently and cover all relevant edge cases.

  7. Commit History: Contributors should avoid force-pushing as much as possible. It makes it harder to track incremental changes and review the latest updates.

  8. Template Design Principles Alignment: While reviewing template-related changes in the packages/ directory, ensure they align with the Assumptions and Principles. If any principle feels outdated or no longer applicable, start a discussion these principles are meant to evolve with the project.

  9. Reduce Scope When Needed: If an issue or PR feels too large or complex, consider splitting it and creating follow-up issues. Smaller, focused PRs are easier to review and merge.

  10. Bot Comments: As reviewers, check that contributors have appropriately addressed comments or suggestions made by automated bots. If there are bot comments the reviewer disagrees with, react to them or mark them as resolved, so the review history remains clear and accurate.

@coderabbitai
Copy link
Copy Markdown

coderabbitai bot commented Mar 25, 2026

📝 Walkthrough

Walkthrough

Added a Jest test suite that exercises isGenerationConditionMet across parameter-driven and subject/JMESPath-driven conditional cases, deprecated conditionalFiles behavior, server-aware JMESPath resolution, validation outcomes, and edge cases for missing or undefined values.

Changes

Cohort / File(s) Summary
Test Suite for Conditional Generation
apps/generator/test/conditionalGeneration.test.js
New comprehensive Jest tests (≈321 lines) for isGenerationConditionMet: covers no-match behavior, parameter-based conditions (with/without validate and parameter undefined), subject-based JMESPath resolution (including servers().get() merging and missing-server cases), deprecated conditionalFiles path and precedence, validate failures and "silent false" scenarios, and mocked logging (loglevel) and ../lib/logMessages).

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title follows Conventional Commits guidelines with 'test:' prefix, uses imperative mood ('add'), and clearly summarizes the main change of adding a comprehensive test suite for conditionalGeneration.js.
Linked Issues check ✅ Passed The PR fully addresses all coding objectives from issue #1970: providing comprehensive test coverage for lib/conditionalGeneration.js across parameter-based, subject-based, and deprecated configuration scenarios, validating complex evaluation logic to prevent regressions.
Out of Scope Changes check ✅ Passed All changes are in-scope: the single file modification (conditionalGeneration.test.js) contains only tests directly supporting the coverage objectives specified in issue #1970, with no unrelated alterations.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

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.

@shivansh-source
Copy link
Copy Markdown
Author

shivansh-source commented Mar 25, 2026

/cc @derberg @Adi-204

Copy link
Copy Markdown

@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

🧹 Nitpick comments (4)
apps/generator/test/conditionalGeneration.test.js (4)

293-295: Remove extraneous empty comment line.

✏️ Cleanup
   // validateStatus – missing validate function (the "silent false" bug guard)
-  // 
   describe('validateStatus – missing validate function', () => {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/generator/test/conditionalGeneration.test.js` around lines 293 - 295,
Remove the stray empty comment line immediately above the describe block for
"validateStatus – missing validate function" so the comment block is concise;
update the comment sequence that currently reads "// validateStatus – missing
validate function" followed by an empty "// " to just the single comment line
before the describe('validateStatus – missing validate function', () => { ... })
block.

33-42: Add missing JSDoc parameter documentation.

Per coding guidelines, JSDoc should include parameter types. This helper mirrors makeConditionalGenerationConfig but lacks the @param tags.

📝 Suggested JSDoc addition
 /**
  * Build a minimal templateConfig with conditionalFiles (deprecated API).
+ *
+ * `@param` {string} path          - The matched condition path key
+ * `@param` {object} conditionOpts - Any subset of { subject, parameter, validate }
  */
 function makeConditionalFilesConfig(path, conditionOpts) {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/generator/test/conditionalGeneration.test.js` around lines 33 - 42, The
JSDoc for makeConditionalFilesConfig is missing `@param` annotations; update the
comment above the function makeConditionalFilesConfig to include `@param` {string}
path and `@param` {Record<string, any> | object} conditionOpts (or the same types
used by makeConditionalGenerationConfig) and a short description for each
parameter so the helper mirrors the existing JSDoc style and types used by
makeConditionalGenerationConfig.

1-5: Fix JSDoc formatting inconsistency.

Lines 3-4 have excessive leading whitespace that breaks the alignment of the documentation block.

✏️ Suggested fix
 /**
  * Comprehensive unit tests for lib/conditionalGeneration.js
-    * Focuses on the isGenerationConditionMet function which determines whether a given file path should be generated based on the template configuration and AsyncAPI document.    * Covers various scenarios including parameter-based conditions, subject-based conditions using JMESPath, and the deprecated conditionalFiles API.
-    * Mocks loglevel and logMessages to verify correct logging behavior for matched conditions and not-generated cases.             
+ * Focuses on the isGenerationConditionMet function which determines whether
+ * a given file path should be generated based on the template configuration
+ * and AsyncAPI document.
+ * Covers various scenarios including parameter-based conditions, subject-based
+ * conditions using JMESPath, and the deprecated conditionalFiles API.
+ * Mocks loglevel and logMessages to verify correct logging behavior for matched
+ * conditions and not-generated cases.
  */
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/generator/test/conditionalGeneration.test.js` around lines 1 - 5, Adjust
the JSDoc block at the top of the test file so the comment lines are
consistently aligned: remove the excessive leading whitespace on the third and
fourth lines so each line starts with " * " (matching the standard JSDoc
alignment used around the description of isGenerationConditionMet), ensuring the
doc block reads as a contiguous, properly formatted comment describing the tests
for isGenerationConditionMet and related scenarios.

190-199: Misleading test description.

The test name claims "does not include server key" but looking at the implementation (context snippet 2, lines 113-116), the server key is always included in the JMESPath search object—it's just set to undefined when templateParams.server is absent. The test passes because the subject 'channels."/user"' resolves independently of the server key.

Consider updating the description for accuracy:

📝 Suggested description update
-    it('does not include server key when templateParams.server is absent', async () => {
+    it('sets server to undefined in JMESPath object when templateParams.server is absent', async () => {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/generator/test/conditionalGeneration.test.js` around lines 190 - 199,
The test title is misleading: the code under test (isGenerationConditionMet
called with config from makeConditionalGenerationConfig) always includes a
server field in the JMESPath search object (possibly undefined) so the assertion
is actually verifying that the subject 'channels."/user"' resolves regardless of
templateParams.server; update the test description to reflect that behavior
(e.g., "skips server-dependent condition when templateParams.server is absent"
or "does not require templateParams.server for channel subject resolution") so
it accurately describes what is being validated by makeAsyncapiDocument,
makeConditionalGenerationConfig, PATH and isGenerationConditionMet.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/generator/test/conditionalGeneration.test.js`:
- Around line 43-50: The helper makeAsyncapiDocument creates fresh mocks each
time servers() is called which breaks call assertions; change it to create and
reuse a single serversMock object (with a persistent get mock that returns
either a serverMock or undefined) and have servers() return that same
serversMock so expect(doc.servers().get).toHaveBeenCalledWith('myServer')
targets the same mock; update makeAsyncapiDocument to construct a serverMock and
serversMock once (reused across calls) and ensure json() mocks still return the
provided jsonData/serverData, and also add JSDoc above makeAsyncapiDocument
describing parameters and return shape per project guidelines.

---

Nitpick comments:
In `@apps/generator/test/conditionalGeneration.test.js`:
- Around line 293-295: Remove the stray empty comment line immediately above the
describe block for "validateStatus – missing validate function" so the comment
block is concise; update the comment sequence that currently reads "//
validateStatus – missing validate function" followed by an empty "// " to just
the single comment line before the describe('validateStatus – missing validate
function', () => { ... }) block.
- Around line 33-42: The JSDoc for makeConditionalFilesConfig is missing `@param`
annotations; update the comment above the function makeConditionalFilesConfig to
include `@param` {string} path and `@param` {Record<string, any> | object}
conditionOpts (or the same types used by makeConditionalGenerationConfig) and a
short description for each parameter so the helper mirrors the existing JSDoc
style and types used by makeConditionalGenerationConfig.
- Around line 1-5: Adjust the JSDoc block at the top of the test file so the
comment lines are consistently aligned: remove the excessive leading whitespace
on the third and fourth lines so each line starts with " * " (matching the
standard JSDoc alignment used around the description of
isGenerationConditionMet), ensuring the doc block reads as a contiguous,
properly formatted comment describing the tests for isGenerationConditionMet and
related scenarios.
- Around line 190-199: The test title is misleading: the code under test
(isGenerationConditionMet called with config from
makeConditionalGenerationConfig) always includes a server field in the JMESPath
search object (possibly undefined) so the assertion is actually verifying that
the subject 'channels."/user"' resolves regardless of templateParams.server;
update the test description to reflect that behavior (e.g., "skips
server-dependent condition when templateParams.server is absent" or "does not
require templateParams.server for channel subject resolution") so it accurately
describes what is being validated by makeAsyncapiDocument,
makeConditionalGenerationConfig, PATH and isGenerationConditionMet.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: f6540435-36ce-4ee7-bd56-620c606e9254

📥 Commits

Reviewing files that changed from the base of the PR and between 9e53861 and d6a8e46.

📒 Files selected for processing (1)
  • apps/generator/test/conditionalGeneration.test.js

Signed-off-by: shivansh-source <shivanshsiddhi1234@gmail.com>
@sonarqubecloud
Copy link
Copy Markdown

Copy link
Copy Markdown

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

🧹 Nitpick comments (2)
apps/generator/test/conditionalGeneration.test.js (2)

31-40: Add complete JSDoc documentation for consistency.

The makeConditionalFilesConfig helper is missing @param and @returns tags, and makeConditionalGenerationConfig is missing the @returns tag. For consistency with makeAsyncapiDocument, consider adding complete documentation.

📝 Proposed JSDoc additions
 /**
  * Build a minimal templateConfig with conditionalGeneration entries.
  *
  * `@param` {string} path          - The matched condition path key
  * `@param` {object} conditionOpts - Any subset of { subject, parameter, validate }
+ * `@returns` {object} A templateConfig object with conditionalGeneration
  */
 function makeConditionalGenerationConfig(path, conditionOpts) {
 /**
  * Build a minimal templateConfig with conditionalFiles (deprecated API).
+ *
+ * `@param` {string} path          - The matched condition path key
+ * `@param` {object} conditionOpts - Any subset of { subject, parameter, validate }
+ * `@returns` {object} A templateConfig object with conditionalFiles
  */
 function makeConditionalFilesConfig(path, conditionOpts) {

As per coding guidelines: "Write clear and consistent JSDoc comments for functions, including parameter types, return values, and error conditions."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/generator/test/conditionalGeneration.test.js` around lines 31 - 40,
Update the JSDoc for the helper functions to include complete tags: add `@param`
and `@returns` to makeConditionalFilesConfig (documenting the path: string and
conditionOpts: object, and that it returns an object with a conditionalFiles
map), and add a `@returns` tag to makeConditionalGenerationConfig describing its
return shape; target the function names makeConditionalFilesConfig and
makeConditionalGenerationConfig and ensure types and brief descriptions match
existing style used by makeAsyncapiDocument.

285-293: Test name claims "silent" behavior but doesn't verify it.

This test is named "(silent false)" implying no logging occurs, but it doesn't assert that log.debug was not called. The test at lines 323-329 tests the identical scenario and properly verifies the silent behavior with expect(log.debug).not.toHaveBeenCalled().

Consider either removing this duplicate test or adding the missing assertion for consistency.

♻️ Option 1: Add the missing assertion
     it('returns false when conditionalFiles validate is missing (silent false)', async () => {
       const doc = makeAsyncapiDocument({ info: { title: 'Test' } });
       const config = makeConditionalFilesConfig(PATH, {
         subject: 'info.title',
         // no validate
       });
       const result = await isGenerationConditionMet(config, PATH, {}, doc);
       expect(result).toBe(false);
+      expect(log.debug).not.toHaveBeenCalled();
     });
♻️ Option 2: Remove this test (covered by lines 323-329)

The test at lines 323-329 already covers this exact scenario with the proper silence assertion.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/generator/test/conditionalGeneration.test.js` around lines 285 - 293,
The test "returns false when conditionalFiles validate is missing (silent
false)" duplicates behavior already covered later but is missing the silence
assertion; update this test (the one calling isGenerationConditionMet with
config from makeConditionalFilesConfig and doc from makeAsyncapiDocument) to
include expect(log.debug).not.toHaveBeenCalled() after the existing
expect(result).toBe(false), or alternatively remove this duplicate test entirely
since the identical scenario is asserted with silence in the later test that
already verifies log.debug was not called.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@apps/generator/test/conditionalGeneration.test.js`:
- Around line 31-40: Update the JSDoc for the helper functions to include
complete tags: add `@param` and `@returns` to makeConditionalFilesConfig
(documenting the path: string and conditionOpts: object, and that it returns an
object with a conditionalFiles map), and add a `@returns` tag to
makeConditionalGenerationConfig describing its return shape; target the function
names makeConditionalFilesConfig and makeConditionalGenerationConfig and ensure
types and brief descriptions match existing style used by makeAsyncapiDocument.
- Around line 285-293: The test "returns false when conditionalFiles validate is
missing (silent false)" duplicates behavior already covered later but is missing
the silence assertion; update this test (the one calling
isGenerationConditionMet with config from makeConditionalFilesConfig and doc
from makeAsyncapiDocument) to include expect(log.debug).not.toHaveBeenCalled()
after the existing expect(result).toBe(false), or alternatively remove this
duplicate test entirely since the identical scenario is asserted with silence in
the later test that already verifies log.debug was not called.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 1c229222-1f9f-4590-9793-8710a2e451b1

📥 Commits

Reviewing files that changed from the base of the PR and between d6a8e46 and 7eceb3c.

📒 Files selected for processing (1)
  • apps/generator/test/conditionalGeneration.test.js

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.

test: Add comprehensive test suite for conditionalGeneration.js

2 participants