Skip to content

test: added tests for isGenerationConditionMet and conditionalParameterGeneration#1977

Closed
shivansh-source wants to merge 1 commit intoasyncapi:masterfrom
shivansh-source:condgentest
Closed

test: added tests for isGenerationConditionMet and conditionalParameterGeneration#1977
shivansh-source wants to merge 1 commit intoasyncapi:masterfrom
shivansh-source:condgentest

Conversation

@shivansh-source
Copy link

@shivansh-source shivansh-source commented Feb 10, 2026

document update and test are wip !

Description

  • Add comprehensive test suite for conditionalGeneration.js (Part 1 of 2)
  • Test isGenerationConditionMet() with various configurations
  • Test conditionalParameterGeneration() with parameter validation
  • Mock dependencies: loglevel, jmespath, logMessages
  • Achieve >70% coverage for tested functions"

Related issue(s)
#1970

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Fixed conditional generation handling of subject and parameter-based conditions.
    • Enhanced error handling for missing or null parameter values with improved debugging.
    • Improved validation flow and source value checks.
  • Tests

    • Added comprehensive test coverage for conditional generation scenarios, parameter validation, edge cases, and integration workflows.

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

changeset-bot bot commented Feb 10, 2026

⚠️ No Changeset found

Latest commit: e0c678d

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.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

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

coderabbitai bot commented Feb 10, 2026

📝 Walkthrough

Walkthrough

The implementation modifies conditional generation logic by adding early branching for subject and parameter condition types, fixing argument passing to conditionalSubjectGeneration, improving null-safe checks, and replacing deprecated paths. A comprehensive test suite is added to verify multiple evaluation branches, server context injection, parameter validation, edge cases, and integration scenarios.

Changes

Cohort / File(s) Summary
Implementation Changes
apps/generator/lib/conditionalGeneration.js
Early branching for subject/parameter conditions; fixed missing templateParams argument; null-safe source checks; improved null/undefined parameter handling with debug logging; replaced deprecated paths.
Test Suite
apps/generator/test/conditionalGeneration.test.js
New comprehensive test coverage for isGenerationConditionMet including subject-based evaluation, parameter validation, server context injection, JMESPath handling, deprecated conditionalFiles paths, edge cases, and integration scenarios.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~30 minutes

🚥 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 uses the 'test:' prefix and imperative mood, clearly describing the addition of tests for two specific functions, which aligns with the actual changes in the PR.
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 docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

Tip

Issue Planner is now in beta. Read the docs and try it out! Share your feedback on Discord.


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.

Copy link
Contributor

@github-actions github-actions bot left a comment

Choose a reason for hiding this comment

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

Welcome to AsyncAPI. Thanks a lot for creating your first pull request. Please check out our contributors guide useful for opening a pull request.
Keep in mind there are also other channels you can use to interact with AsyncAPI community. For more details check out this issue.

@sonarqubecloud
Copy link

@shivansh-source shivansh-source changed the title test: add tests for isGenerationConditionMet and conditionalParameterGeneration test: added tests for isGenerationConditionMet and conditionalParameterGeneration Feb 10, 2026
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: 6

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (3)
apps/generator/lib/conditionalGeneration.js (3)

71-80: ⚠️ Potential issue | 🔴 Critical

conditionalParameterGeneration never invokes the validate function.

The function checks only whether the parameter value is null/undefined and returns true for any other value. The validate callback from the config is completely ignored, so parameter-based validations (e.g., enum checks, boolean flags) always pass.

This will cause tests like "should return false when parameter value fails validation" and "should support enum-style parameter validation" to fail.

🐛 Proposed fix: delegate to `validateStatus` after the null guard
 async function conditionalParameterGeneration(templateConfig, matchedConditionPath, templateParams) {
   const conditionalGenerationConfig = templateConfig.conditionalGeneration?.[matchedConditionPath];
   const parameterName = conditionalGenerationConfig.parameter;
   const parameterValue = templateParams[parameterName];
   if (parameterValue == null) {
     log.debug(logMessage.relativeSourceFileNotGenerated(matchedConditionPath, parameterName));
     return false;
   }
-  return true;
+  return validateStatus(parameterValue, matchedConditionPath, templateConfig);
 }

29-57: ⚠️ Potential issue | 🟠 Major

Early branching makes lines 35-57 unreachable dead code.

The new if (config.subject) / else if (config.parameter) at lines 29-33 returns before the existing logic at lines 35-57 is ever reached:

  • If config.subject is truthy → early return at line 30.
  • If config.parameter is truthy → early return at line 32.
  • If neither → subject at line 35 is guaranteed falsy, so line 39's && subject is always false, and line 48's if (subject) is always false.

Notably, conditionalFilesGenerationDeprecatedVersion at line 40 is called but never defined in this file — it would throw a ReferenceError if reached. The early branching masks this but the dead code is confusing and fragile.

Additionally, the early branch uses config (which may come from conditionFilesGeneration), but conditionalSubjectGeneration internally resolves its own config from conditionalGeneration first (line 108). This mismatch means the trigger condition (config.subject from deprecated config) may differ from the config actually used inside the function.

Either remove lines 35-57 entirely (since the early branch handles all cases), or restructure so there's a single, clear decision path.

♻️ Proposed simplification: remove dead code
   const config = Object.keys(conditionFilesGeneration).length > 0 
     ? conditionFilesGeneration 
     : conditionalGeneration;
-    if (config.subject) {
-  return conditionalSubjectGeneration(asyncapiDocument, templateConfig, matchedConditionPath, templateParams);
-  } else if (config.parameter) {
-  return conditionalParameterGeneration(templateConfig,   matchedConditionPath, templateParams);
-  }
-
-  const subject = config?.subject;
-
-  // conditionalFiles becomes deprecated with this PR, and soon will be removed.
-  // TODO: https://github.com/asyncapi/generator/issues/1553
-  if (Object.keys(conditionFilesGeneration).length > 0 && subject) {
-    return conditionalFilesGenerationDeprecatedVersion(
-      asyncapiDocument,
-      templateConfig,
-      matchedConditionPath,
-      templateParams
-    );
-  } else if (Object.keys(conditionalGeneration).length > 0) {
-    // Case when the subject is present in conditionalGeneration
-    if (subject) {
-      return conditionalSubjectGeneration(
-        asyncapiDocument,
-        templateConfig,
-        matchedConditionPath,
-        templateParams  // FIX: was missing in original, caused TypeError on templateParams.server
-      );
-    }
-    return conditionalParameterGeneration(templateConfig, matchedConditionPath, templateParams);
-  }
+  if (config.subject) {
+    return conditionalSubjectGeneration(asyncapiDocument, templateConfig, matchedConditionPath, templateParams);
+  } else if (config.parameter) {
+    return conditionalParameterGeneration(templateConfig, matchedConditionPath, templateParams);
+  }

82-101: ⚠️ Potential issue | 🟡 Minor

Duplicate JSDoc block for conditionalSubjectGeneration.

Lines 82-91 and 92-101 contain the same doc comment. Remove one.

Proposed fix
-/**
- * Determines whether a file should be conditionally included based on the provided subject expression
- * and optional validation logic defined in the template configuration.
- * `@private`
- * `@param` {Object} asyncapiDocument - The parsed AsyncAPI document instance used for context evaluation.
- * `@param` {Object} templateConfig - The configuration object that contains `conditionalFiles` rules.
- * `@param` {string} matchedConditionPath - The path of the file/folder being conditionally generated.
- * `@param` {Object} templateParams - The parameters passed to the generator, usually user input or default values.
- * `@returns` {Boolean} - Returns `true` if the file should be included; `false` if it should be skipped.
- */
 /**
  * Determines whether a file should be conditionally included based on the provided subject expression
  * and optional validation logic defined in the template configuration.
🤖 Fix all issues with AI agents
In `@apps/generator/lib/conditionalGeneration.js`:
- Around line 29-33: The if/else-if branch uses inconsistent indentation and an
extra space after templateConfig; update the block around the config check so
indentation matches the project's 2-space style and remove the double space in
the call to conditionalParameterGeneration(templateConfig, matchedConditionPath,
templateParams); ensure the calls to
conditionalSubjectGeneration(asyncapiDocument, templateConfig,
matchedConditionPath, templateParams) and conditionalParameterGeneration(...)
are indented consistently with surrounding code and use single spaces after
commas.

In `@apps/generator/test/conditionalGeneration.test.js`:
- Around line 435-456: The test descriptions in the
conditionalGeneration.test.js are incorrect and don't match their assertions;
update the test case titles (the it(...) strings) so they accurately reflect the
asserted behavior for isGenerationConditionMet (e.g., change "should return true
when subject is found and no validation function exists" to "should return false
when subject is found and no validation function exists" and change "should
return true when condition is not specified" to "should return undefined when
condition is not specified"), keeping the existing assertions and mocking
(jmespath.search, mockTemplateParams, mockAsyncAPIDocument) unchanged so the
test names match the behavior being tested.
- Around line 159-194: The tests fail because the conditionalParameterGeneration
logic (used by isGenerationConditionMet / conditionalGeneration) only checks
parameter presence (null/undefined) and never calls the provided validate
function; update the implementation in the conditionalParameterGeneration path
to invoke the configured validator (either call the validate function on the
rule object or call validateStatus if that helper exists) with the parameter
value and use its boolean result as the condition. Ensure you reference the rule
under conditionalGeneration[filePath].parameter and
conditionalGeneration[filePath].validate (or the validateStatus helper) so that
cases like { includeDocs: false } and { protocol: 'http' } return false when
validate rejects them, and keep existing logging (log.debug with
logMessage.conditionalGenerationMatched(filePath)) consistent when a match
occurs.
- Around line 406-433: The test declares mockGet with const inside beforeEach so
it isn't available to the it blocks; move the declaration of mockGet to the
outer describe scope (declare let mockGet; above beforeEach) and then assign
mockGet = jest.fn(...) inside beforeEach, ensuring all assertions (e.g.,
expect(mockGet).toHaveBeenCalledWith(...)) and the
mockAsyncAPIDocument.servers.get reference use that hoisted variable; keep
beforeEach assigning mockAsyncAPIDocument.servers.get to mockGet and leave the
rest of the setup intact.
- Around line 364-387: The test's expectations conflict with
isGenerationConditionMet's current flow: when both conditionalFiles and
conditionalGeneration exist the function selects conditionFilesGeneration (the
combined config) but only uses the deprecated validate path if config.subject is
defined, so deprecatedValidate and log.conditionalFilesMatched are never invoked
for the provided mixed config. Fix by either updating the test to reflect
current behavior (assert deprecatedValidate is NOT called and assert the
conditionalParameterGeneration branch behavior) or change
isGenerationConditionMet to prefer the conditionalFiles.validate path when
conditionalFiles contains an entry for filePath (i.e. in
isGenerationConditionMet ensure that when
templateConfig.conditionalFiles[filePath] exists you call its validate with the
resolved subject/value and emit log.conditionalFilesMatched(filePath));
reference isGenerationConditionMet, templateConfig.conditionalFiles,
templateConfig.conditionalGeneration, deprecatedValidate, and
log.conditionalFilesMatched when making the change.
- Around line 389-402: Add a missing closing "});" to terminate the
describe('isGenerationConditionMet()') block before the "PART 2" section so that
describe('conditionalSubjectGeneration()'), describe('validateStatus()'),
describe('conditionalFilesGenerationDeprecatedVersion()' ) and the Integration
tests are not nested inside isGenerationConditionMet(); specifically insert the
closing for describe('isGenerationConditionMet()') immediately before the
comment block that begins "PART 2: Tests for conditionalSubjectGeneration,
validateStatus, and deprecated functions". After adding that closing, remove the
extra redundant "});" near the end of the file (around the previously noted
closing at ~line 1050) to keep brace counts balanced.
🧹 Nitpick comments (1)
apps/generator/test/conditionalGeneration.test.js (1)

431-432: Prefer jest.mock('jmespath', ...) over monkey-patching the module export.

Directly assigning jmespath.search = jest.fn() in beforeEach replaces the real implementation for all subsequent tests in the file. The earlier tests (lines 48–151) rely on real jmespath behavior and would break if test execution order ever changed (e.g., --randomize). Using jest.mock with jest.requireActual gives you controlled mocking with proper isolation via jest.restoreAllMocks().

Comment on lines +29 to +33
if (config.subject) {
return conditionalSubjectGeneration(asyncapiDocument, templateConfig, matchedConditionPath, templateParams);
} else if (config.parameter) {
return conditionalParameterGeneration(templateConfig, matchedConditionPath, templateParams);
}
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

Inconsistent indentation in the early-branch block.

The if/else if block mixes 4-space and 2-space indentation and has a double space after templateConfig, on line 32. If the dead code below is removed (see other comment), this block should use consistent project indentation.

Proposed fix (assuming 2-space project indent)
-    if (config.subject) {
-  return conditionalSubjectGeneration(asyncapiDocument, templateConfig, matchedConditionPath, templateParams);
-  } else if (config.parameter) {
-  return conditionalParameterGeneration(templateConfig,   matchedConditionPath, templateParams);
-  }
+  if (config.subject) {
+    return conditionalSubjectGeneration(asyncapiDocument, templateConfig, matchedConditionPath, templateParams);
+  } else if (config.parameter) {
+    return conditionalParameterGeneration(templateConfig, matchedConditionPath, templateParams);
+  }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (config.subject) {
return conditionalSubjectGeneration(asyncapiDocument, templateConfig, matchedConditionPath, templateParams);
} else if (config.parameter) {
return conditionalParameterGeneration(templateConfig, matchedConditionPath, templateParams);
}
if (config.subject) {
return conditionalSubjectGeneration(asyncapiDocument, templateConfig, matchedConditionPath, templateParams);
} else if (config.parameter) {
return conditionalParameterGeneration(templateConfig, matchedConditionPath, templateParams);
}
🤖 Prompt for AI Agents
In `@apps/generator/lib/conditionalGeneration.js` around lines 29 - 33, The
if/else-if branch uses inconsistent indentation and an extra space after
templateConfig; update the block around the config check so indentation matches
the project's 2-space style and remove the double space in the call to
conditionalParameterGeneration(templateConfig, matchedConditionPath,
templateParams); ensure the calls to
conditionalSubjectGeneration(asyncapiDocument, templateConfig,
matchedConditionPath, templateParams) and conditionalParameterGeneration(...)
are indented consistently with surrounding code and use single spaces after
commas.

Comment on lines +159 to +194
it('should return true when parameter value passes validation', async () => {
const filePath = 'src/docs/';
const templateConfig = {
conditionalGeneration: {
[filePath]: {
parameter: 'includeDocs',
validate: (val) => val === true,
},
},
};

const result = await isGenerationConditionMet(
templateConfig, filePath, { includeDocs: true }, null
);
expect(result).toBe(true);
});

it('should return false when parameter value fails validation', async () => {
const filePath = 'src/docs/';
const templateConfig = {
conditionalGeneration: {
[filePath]: {
parameter: 'includeDocs',
validate: (val) => val === true,
},
},
};

const result = await isGenerationConditionMet(
templateConfig, filePath, { includeDocs: false }, null
);
expect(result).toBe(false);
expect(log.debug).toHaveBeenCalledWith(
logMessage.conditionalGenerationMatched(filePath)
);
});
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Multiple parameter-validation tests will fail due to the implementation bug.

Since conditionalParameterGeneration only checks for null/undefined and never invokes validate (see review comment on the implementation file):

  • Line 190: { includeDocs: false }false != null → returns true, but test expects false.
  • Line 229: { protocol: 'http' }'http' != null → returns true, but test expects false.

These tests correctly describe the expected behavior. Once the implementation is fixed to call validateStatus (or invoke validate directly), they should pass.

Also applies to: 213-231

🤖 Prompt for AI Agents
In `@apps/generator/test/conditionalGeneration.test.js` around lines 159 - 194,
The tests fail because the conditionalParameterGeneration logic (used by
isGenerationConditionMet / conditionalGeneration) only checks parameter presence
(null/undefined) and never calls the provided validate function; update the
implementation in the conditionalParameterGeneration path to invoke the
configured validator (either call the validate function on the rule object or
call validateStatus if that helper exists) with the parameter value and use its
boolean result as the condition. Ensure you reference the rule under
conditionalGeneration[filePath].parameter and
conditionalGeneration[filePath].validate (or the validateStatus helper) so that
cases like { includeDocs: false } and { protocol: 'http' } return false when
validate rejects them, and keep existing logging (log.debug with
logMessage.conditionalGenerationMatched(filePath)) consistent when a match
occurs.

Comment on lines +364 to +387
it('should use conditionalFiles path when both conditionalFiles and conditionalGeneration are present', async () => {
const filePath = 'src/both.js';
const asyncapiDoc = makeMockDocument({ info: { version: '2.0.0' } });

const deprecatedValidate = jest.fn((val) => val === '1.0.0'); // returns false for '2.0.0'

const templateConfig = {
conditionalFiles: {
[filePath]: { validate: deprecatedValidate },
},
conditionalGeneration: {
[filePath]: { subject: 'info.version' },
},
};

const result = await isGenerationConditionMet(
templateConfig, filePath, {}, asyncapiDoc
);
expect(result).toBe(false);
expect(deprecatedValidate).toHaveBeenCalledWith('2.0.0');
expect(log.debug).toHaveBeenCalledWith(
logMessage.conditionalFilesMatched(filePath)
);
});
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Test expectations may not match the actual code flow.

Given the config:

conditionalFiles:      { [filePath]: { validate: deprecatedValidate } }       // no subject
conditionalGeneration: { [filePath]: { subject: 'info.version' } }            // no validate

At line 26-28, config = conditionFilesGeneration (because it has keys). Since config.subject is undefined (the deprecated entry has no subject), the early branch at line 29 doesn't fire. The fallthrough eventually reaches conditionalParameterGeneration (not the deprecated path), which never invokes deprecatedValidate.

The assertions at line 383 (expect(deprecatedValidate).toHaveBeenCalledWith('2.0.0')) and line 384-386 (the conditionalFilesMatched log) won't hold. The comment block at lines 390-395 also describes a flow that doesn't match the implementation.

Please re-examine the intended behavior for this mixed-config scenario and update either the implementation or the test accordingly.

🤖 Prompt for AI Agents
In `@apps/generator/test/conditionalGeneration.test.js` around lines 364 - 387,
The test's expectations conflict with isGenerationConditionMet's current flow:
when both conditionalFiles and conditionalGeneration exist the function selects
conditionFilesGeneration (the combined config) but only uses the deprecated
validate path if config.subject is defined, so deprecatedValidate and
log.conditionalFilesMatched are never invoked for the provided mixed config. Fix
by either updating the test to reflect current behavior (assert
deprecatedValidate is NOT called and assert the conditionalParameterGeneration
branch behavior) or change isGenerationConditionMet to prefer the
conditionalFiles.validate path when conditionalFiles contains an entry for
filePath (i.e. in isGenerationConditionMet ensure that when
templateConfig.conditionalFiles[filePath] exists you call its validate with the
resolved subject/value and emit log.conditionalFilesMatched(filePath));
reference isGenerationConditionMet, templateConfig.conditionalFiles,
templateConfig.conditionalGeneration, deprecatedValidate, and
log.conditionalFilesMatched when making the change.

Comment on lines +389 to +402
});
/**
* Key insight: With the preference for conditionalGeneration, config uses new (with subject).
* validateStatus() falls back to conditionalFiles.validate since new has no validate.
* Subject resolves to '2.0.0' → deprecatedValidate('2.0.0') → false.
* Log uses conditionalGenerationMatched since new config exists.
*/

// ============================================================================
// PART 2: Tests for conditionalSubjectGeneration, validateStatus,
// and deprecated functions
// ============================================================================

describe('conditionalSubjectGeneration()', () => {
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Missing }); to close describe('isGenerationConditionMet()') before PART 2.

Line 389 closes describe('edge cases'), but there's no corresponding }); to close describe('isGenerationConditionMet()') before the PART 2 describes begin at line 402. As a result, conditionalSubjectGeneration(), validateStatus(), conditionalFilesGenerationDeprecatedVersion(), and Integration tests are all nested inside isGenerationConditionMet(), producing misleading test output hierarchy.

🐛 Proposed fix: close the describe block
     });
+  });
   /**
-  * Key insight: With the preference for conditionalGeneration, config uses new (with subject).
+ /**
+  * Key insight: With the preference for conditionalGeneration, config uses new (with subject).

You'll also need to remove one of the closing }); at the end of the file (around line 1050) to keep brace counts balanced.

🤖 Prompt for AI Agents
In `@apps/generator/test/conditionalGeneration.test.js` around lines 389 - 402,
Add a missing closing "});" to terminate the
describe('isGenerationConditionMet()') block before the "PART 2" section so that
describe('conditionalSubjectGeneration()'), describe('validateStatus()'),
describe('conditionalFilesGenerationDeprecatedVersion()' ) and the Integration
tests are not nested inside isGenerationConditionMet(); specifically insert the
closing for describe('isGenerationConditionMet()') immediately before the
comment block that begins "PART 2: Tests for conditionalSubjectGeneration,
validateStatus, and deprecated functions". After adding that closing, remove the
extra redundant "});" near the end of the file (around the previously noted
closing at ~line 1050) to keep brace counts balanced.

Comment on lines +406 to +433
beforeEach(() => {
jest.clearAllMocks();
const mockGet = jest.fn((serverName) => ({
json: () => ({ url: 'mqtt://test.mosquitto.org', protocol: 'mqtt' })
}));

mockAsyncAPIDocument = {
json: jest.fn(() => ({
asyncapi: '2.0.0',
info: { title: 'Test API', version: '1.0.0' },
channels: {
'user/signup': {},
'user/login': {}
}
})),
servers: jest.fn(() => ({
get: mockGet
}))
};

mockTemplateParams = {
server: 'production',
customParam: 'testValue'
};

jmespath.search = jest.fn();
log.debug = jest.fn();
});
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

mockGet is not accessible in the it blocks — test will throw ReferenceError.

mockGet is declared with const inside the beforeEach callback at line 408, so it's scoped to that callback. The assertion at line 547 (expect(mockGet).toHaveBeenCalledWith(...)) references a variable that doesn't exist in the it block's scope.

🐛 Proposed fix: hoist `mockGet` to `describe` scope
   describe('conditionalSubjectGeneration()', () => {
     let mockAsyncAPIDocument;
     let mockTemplateParams;
+    let mockGet;
 
     beforeEach(() => {
       jest.clearAllMocks();
-      const mockGet = jest.fn((serverName) => ({
+      mockGet = jest.fn((serverName) => ({
          json: () => ({ url: 'mqtt://test.mosquitto.org', protocol: 'mqtt' })
       }));

Also applies to: 527-556

🤖 Prompt for AI Agents
In `@apps/generator/test/conditionalGeneration.test.js` around lines 406 - 433,
The test declares mockGet with const inside beforeEach so it isn't available to
the it blocks; move the declaration of mockGet to the outer describe scope
(declare let mockGet; above beforeEach) and then assign mockGet = jest.fn(...)
inside beforeEach, ensuring all assertions (e.g.,
expect(mockGet).toHaveBeenCalledWith(...)) and the
mockAsyncAPIDocument.servers.get reference use that hoisted variable; keep
beforeEach assigning mockAsyncAPIDocument.servers.get to mockGet and leave the
rest of the setup intact.

Comment on lines +435 to +456
it('should return true when subject is found and no validation function exists', async () => {
const templateConfig = {
conditionalGeneration: {
'path/to/file': {
subject: 'channels'
}
}
};

jmespath.search.mockReturnValue({ 'user/signup': {} });

const result = await isGenerationConditionMet(
templateConfig,
'path/to/file',
mockTemplateParams,
mockAsyncAPIDocument
);

// When there's no validate function, validateStatus returns false
expect(result).toBe(false);
expect(jmespath.search).toHaveBeenCalled();
});
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

Test names contradict their assertions.

  • Line 435: "should return true when subject is found and no validation function exists" — but asserts false (line 454).
  • Line 458: "should return true when condition is not specified" — but asserts undefined (line 472).

Misleading names make future debugging harder.

Proposed fix
-    it('should return true when subject is found and no validation function exists', async () => {
+    it('should return false when subject is found but no validation function exists', async () => {
-    it('should return true when condition is not specified', async () => {
+    it('should return undefined when condition is not specified', async () => {

Also applies to: 458-473

🤖 Prompt for AI Agents
In `@apps/generator/test/conditionalGeneration.test.js` around lines 435 - 456,
The test descriptions in the conditionalGeneration.test.js are incorrect and
don't match their assertions; update the test case titles (the it(...) strings)
so they accurately reflect the asserted behavior for isGenerationConditionMet
(e.g., change "should return true when subject is found and no validation
function exists" to "should return false when subject is found and no validation
function exists" and change "should return true when condition is not specified"
to "should return undefined when condition is not specified"), keeping the
existing assertions and mocking (jmespath.search, mockTemplateParams,
mockAsyncAPIDocument) unchanged so the test names match the behavior being
tested.

@Adi-204
Copy link
Member

Adi-204 commented Feb 11, 2026

Thanks for the contribution. I’m closing this PR because, while there is an existing issue, it was not approved or opened for contribution before the pull request was submitted.

Please make sure to follow the contribution guidelines, which explain when issues are considered ready for implementation and when pull requests are appropriate

@Adi-204 Adi-204 closed this Feb 11, 2026
@shivansh-source
Copy link
Author

i messaged u on slack can u check @Adi-204

@shivansh-source shivansh-source deleted the condgentest branch February 15, 2026 12:59
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.

3 participants