Skip to content

test(websocket-js): add unit tests for CompileOperationSchemas component#2034

Open
SHUBHANSHU602 wants to merge 2 commits intoasyncapi:masterfrom
SHUBHANSHU602:unit-test-javascript
Open

test(websocket-js): add unit tests for CompileOperationSchemas component#2034
SHUBHANSHU602 wants to merge 2 commits intoasyncapi:masterfrom
SHUBHANSHU602:unit-test-javascript

Conversation

@SHUBHANSHU602
Copy link
Copy Markdown
Contributor

@SHUBHANSHU602 SHUBHANSHU602 commented Mar 28, 2026

🧪 Add unit tests for CompileOperationSchemas component

Summary

This PR introduces unit tests for the CompileOperationSchemas component in the WebSocket JavaScript client template.

The component is responsible for generating a method (compileOperationSchemas) as a string using the Text component from @asyncapi/generator-react-sdk.


What is tested

  • Returns null when:

    • sendOperations is undefined
    • sendOperations is an empty array
  • Renders a Text component when sendOperations are provided

  • Verifies that the generated output string contains key parts:

    • async compileOperationSchemas()
    • this.schemasCompiled
    • compileSchemasByOperationId

Screenshot 2026-03-28 122237

Resolves #1935

Summary by CodeRabbit

  • Tests
    • Added test suites for WebSocket client operation schema compilation. Covers behavior when operation lists are undefined, empty, or populated, including snapshot-based rendering checks and assertions that compiled schema output is produced when operations are present.

@changeset-bot
Copy link
Copy Markdown

changeset-bot bot commented Mar 28, 2026

⚠️ No Changeset found

Latest commit: 8780afa

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
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 28, 2026

📝 Walkthrough

Walkthrough

Adds two new Jest test files for the CompileOperationSchemas component: one low-level test asserting null/element returns and rendered content, and one component-level test covering snapshot, empty array, and undefined sendOperations cases.

Changes

Cohort / File(s) Summary
Unit tests (logic/assertions)
packages/templates/clients/websocket/javascript/test/CompileOperationSchemas.test.js
New Jest tests asserting behavior when sendOperations is undefined, empty, or populated; verifies returned value nullness, element type (Text), and presence of specific strings in rendered output.
Component tests (render/snapshot)
packages/templates/clients/websocket/javascript/test/components/CompileOperationSchemas.test.js
New React-rendering tests: snapshot test for sendOperations={['testOperation']}, and checks that empty or omitted sendOperations produce empty string output.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 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 pull request title clearly summarizes the main change: adding unit tests for the CompileOperationSchemas component following Conventional Commits guidelines with 'test:' prefix in imperative mood.
Linked Issues check ✅ Passed The PR fully addresses the requirements from issue #1935 by adding comprehensive unit tests for CompileOperationSchemas that validate conditional logic and edge cases with 100% code coverage.
Out of Scope Changes check ✅ Passed All changes are directly related to implementing unit tests for CompileOperationSchemas as specified in issue #1935, with no extraneous modifications detected.
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 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.

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 (1)
packages/templates/clients/websocket/javascript/test/CompileOperationSchemas.test.js (1)

15-30: Make JSX-tree assertions less brittle.

Current assertions depend on exact Fragment child shape (result.props.children...). A small JSX restructuring in CompileOperationSchemas could break tests without changing behavior.

Suggested refactor
 import { CompileOperationSchemas } from '../components/CompileOperationSchemas';
 import { Text } from '@asyncapi/generator-react-sdk';
 
 describe('CompileOperationSchemas', () => {
+  function getTextNode(result) {
+    const children = Array.isArray(result?.props?.children)
+      ? result.props.children
+      : [result?.props?.children];
+    return children.find((child) => child?.type === Text);
+  }
+
   it('should return null when sendOperations is undefined', () => {
     const result = CompileOperationSchemas({});
     expect(result).toBeNull();
   });
@@
   it('should render Text component when sendOperations exist', () => {
     const result = CompileOperationSchemas({ sendOperations: ['op1'] });
 
     expect(result).not.toBeNull();
-    expect(result.props.children.type).toBe(Text);
+    const textNode = getTextNode(result);
+    expect(textNode).toBeDefined();
+    expect(textNode.type).toBe(Text);
   });
 
   it('should contain compileOperationSchemas function in output', () => {
     const result = CompileOperationSchemas({ sendOperations: ['op1'] });
-
-    const textContent = result.props.children.props.children;
+    const textNode = getTextNode(result);
+    const textContent = textNode.props.children;
 
     expect(textContent).toContain('async compileOperationSchemas()');
     expect(textContent).toContain('this.schemasCompiled');
     expect(textContent).toContain('compileSchemasByOperationId');
   });
 });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/templates/clients/websocket/javascript/test/CompileOperationSchemas.test.js`
around lines 15 - 30, The tests for CompileOperationSchemas rely on a brittle
traversal of result.props.children; update them to robustly locate the Text node
and its string contents instead: render CompileOperationSchemas into a test
renderer result, use renderer utilities or a traversal (e.g., findAll/recursive
scan) to locate the child whose type is Text (referencing
CompileOperationSchemas and Text), then assert that at least one Text node's
rendered string contains 'async compileOperationSchemas()',
'this.schemasCompiled', and 'compileSchemasByOperationId' rather than chaining
result.props.children... to reach the strings.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In
`@packages/templates/clients/websocket/javascript/test/CompileOperationSchemas.test.js`:
- Around line 15-30: The tests for CompileOperationSchemas rely on a brittle
traversal of result.props.children; update them to robustly locate the Text node
and its string contents instead: render CompileOperationSchemas into a test
renderer result, use renderer utilities or a traversal (e.g., findAll/recursive
scan) to locate the child whose type is Text (referencing
CompileOperationSchemas and Text), then assert that at least one Text node's
rendered string contains 'async compileOperationSchemas()',
'this.schemasCompiled', and 'compileSchemasByOperationId' rather than chaining
result.props.children... to reach the strings.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 887323da-789c-46cf-9ca0-f841cbcebb09

📥 Commits

Reviewing files that changed from the base of the PR and between bd121dd and 072a984.

📒 Files selected for processing (1)
  • packages/templates/clients/websocket/javascript/test/CompileOperationSchemas.test.js

@Adi-204 Adi-204 self-assigned this Apr 3, 2026
Copy link
Copy Markdown
Member

@Adi-204 Adi-204 left a comment

Choose a reason for hiding this comment

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

@SHUBHANSHU602 the tests are incorrect. First, you need to create a components folder inside the test directory to match the expected structure. Also, we use snapshot testing for components—not unit tests. I’d suggest looking at other templates, such as the Java template, which already has proper component testing in place.
https://github.com/asyncapi/generator/tree/master/packages/templates/clients/websocket/java/quarkus/test/components

@SHUBHANSHU602
Copy link
Copy Markdown
Contributor Author

ohk @Adi-204 I was bit confused about the directory , thanks for guidence I will fix it soon.

@sonarqubecloud
Copy link
Copy Markdown

sonarqubecloud bot commented Apr 5, 2026

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 (1)
packages/templates/clients/websocket/javascript/test/components/CompileOperationSchemas.test.js (1)

13-27: Consider parameterizing the two empty-output cases.

Both tests assert the same outcome for different inputs; it.each can reduce duplication and keep intent clear.

♻️ Optional refactor
-  it('renders empty output when no send operations', async () => {
-    const result = await render(
-      <CompileOperationSchemas sendOperations={[]} />
-    );
-
-    expect(result).toBe('');
-  });
-
-  it('renders empty output when sendOperations is undefined', async () => {
-    const result = await render(
-      <CompileOperationSchemas />
-    );
-
-    expect(result).toBe('');
-  });
+  it.each([
+    { label: 'empty array', sendOperations: [] },
+    { label: 'undefined', sendOperations: undefined },
+  ])('renders empty output when sendOperations is $label', async ({ sendOperations }) => {
+    const result = await render(
+      <CompileOperationSchemas sendOperations={sendOperations} />
+    );
+
+    expect(result).toBe('');
+  });
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In
`@packages/templates/clients/websocket/javascript/test/components/CompileOperationSchemas.test.js`
around lines 13 - 27, Replace the two duplicate tests that call
render(<CompileOperationSchemas sendOperations={[]}/> ) and
render(<CompileOperationSchemas />) with a single parameterized test using
it.each, passing the two inputs (an empty array and undefined) and asserting the
same result; locate the tests that reference CompileOperationSchemas and render
in CompileOperationSchemas.test.js and refactor them to use it.each([...]) with
a descriptive test name while keeping the expect(result).toBe('') assertion.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In
`@packages/templates/clients/websocket/javascript/test/components/CompileOperationSchemas.test.js`:
- Around line 13-27: Replace the two duplicate tests that call
render(<CompileOperationSchemas sendOperations={[]}/> ) and
render(<CompileOperationSchemas />) with a single parameterized test using
it.each, passing the two inputs (an empty array and undefined) and asserting the
same result; locate the tests that reference CompileOperationSchemas and render
in CompileOperationSchemas.test.js and refactor them to use it.each([...]) with
a descriptive test name while keeping the expect(result).toBe('') assertion.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: ddfc8a87-30e3-4e23-8234-a40c06ce1319

📥 Commits

Reviewing files that changed from the base of the PR and between 072a984 and 8780afa.

⛔ Files ignored due to path filters (1)
  • packages/templates/clients/websocket/javascript/test/components/__snapshots__/CompileOperationSchemas.test.js.snap is excluded by !**/*.snap
📒 Files selected for processing (1)
  • packages/templates/clients/websocket/javascript/test/components/CompileOperationSchemas.test.js

@SHUBHANSHU602
Copy link
Copy Markdown
Contributor Author

@Adi-204 let me know if it is ohk now

Copy link
Copy Markdown
Member

@Adi-204 Adi-204 left a comment

Choose a reason for hiding this comment

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

@SHUBHANSHU602 left 2 comments rest looks good!

expect(textContent).toContain('this.schemasCompiled');
expect(textContent).toContain('compileSchemasByOperationId');
});
}); No newline at end of file
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

please delete this test file as we don't need it anymore.


expect(result).toBe('');
});
}); No newline at end of file
Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

just add one more testcase with sendOperations=null

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 component tests for CompileOperationSchemas.js (Js WebSocket Template)

3 participants