Skip to content

test: add unit tests for scripts/compose.ts#5626

Open
codxbrexx wants to merge 6 commits into
asyncapi:masterfrom
codxbrexx:add/unit-tests
Open

test: add unit tests for scripts/compose.ts#5626
codxbrexx wants to merge 6 commits into
asyncapi:masterfrom
codxbrexx:add/unit-tests

Conversation

@codxbrexx

@codxbrexx codxbrexx commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Description

  • Refactored scripts/compose.ts to export getSlug(), genFrontMatter(), and writePost() as named functions, and guarded the inquirer CLI behind a main() function with a process.argv check (same pattern used by build-meetings.ts) — no change to runtime behavior
  • Added tests/scripts/compose.test.ts with 25 tests covering slug generation (kebab-case, special characters, edge cases), front matter output (title fallback, tag parsing, date format, canonical URL), and file writing (success path, untitled fallback, error handling)
  • Removed scripts/compose.ts from coveragePathIgnorePatterns in jest.config.js so coverage is now tracked for this file

Related issue(s)

Resolves #5096

Summary by CodeRabbit

  • Improvements

    • Blog post creation now generates consistent, URL-friendly slugs and writes markdown files safely (won’t overwrite existing posts).
    • Front matter generation is more robust, including improved handling for untitled posts, canonical URLs (including empty), excerpts/spacing, and tag parsing.
  • Tests

    • Added automated coverage for slug generation, front matter rendering, and post file creation, including success and write-failure scenarios.
  • Chores

    • Updated Jest coverage ignore settings to exclude only the intended tooling paths.

@netlify

netlify Bot commented Jul 13, 2026

Copy link
Copy Markdown

Deploy Preview for asyncapi-website ready!

Built without sensitive environment variables

Name Link
🔨 Latest commit a0af92a
🔍 Latest deploy log https://app.netlify.com/projects/asyncapi-website/deploys/6a54f272cd05980008f6c748
😎 Deploy Preview https://deploy-preview-5626--asyncapi-website.netlify.app
📱 Preview on mobile
Toggle QR Code...

QR Code

Use your smartphone camera to open QR code link.
🤖 Make changes Run an agent on this branch

To edit notification comments on pull requests, go to your Netlify project configuration.

@codecov

codecov Bot commented Jul 13, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (3a526ff) to head (a0af92a).
⚠️ Report is 297 commits behind head on master.

Additional details and impacted files
@@            Coverage Diff             @@
##            master     #5626    +/-   ##
==========================================
  Coverage   100.00%   100.00%            
==========================================
  Files           22        24     +2     
  Lines          796       998   +202     
  Branches       146       198    +52     
==========================================
+ Hits           796       998   +202     

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

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@asyncapi-bot

asyncapi-bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

⚡️ Lighthouse report for the changes in this PR:

Category Score
🔴 Performance 41
🟢 Accessibility 98
🟢 Best practices 92
🟢 SEO 100
🔴 PWA 33

Lighthouse ran on https://deploy-preview-5626--asyncapi-website.netlify.app/

@coderabbitai

coderabbitai Bot commented Jul 13, 2026

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 8ec00634-373b-4771-b2bf-0f1ff5218768

📥 Commits

Reviewing files that changed from the base of the PR and between 937acfa and a0af92a.

📒 Files selected for processing (1)
  • scripts/compose.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • scripts/compose.ts

📝 Walkthrough

Walkthrough

The compose script now exports slug, front-matter, and post-writing helpers, separates CLI execution from file creation, removes the script from Jest coverage exclusions, and adds deterministic tests for serialization, slugging, writing, logging, and errors.

Changes

Compose script refactor and coverage

Layer / File(s) Summary
Exported slug and front-matter helpers
scripts/compose.ts
Adds reusable getSlug and exported genFrontMatter functions.
File writing and CLI integration
scripts/compose.ts
Adds writePost, delegates CLI answers to it, and updates direct-execution detection.
Deterministic compose tests
tests/scripts/compose.test.ts, jest.config.js
Tests front matter, slug generation, file writing, logging, errors, and enables coverage for scripts/compose.ts.

Estimated code review effort: 3 (Moderate) | ~20 minutes

Suggested reviewers: akshatnema, anshgoyalevil, asyncapi-bot-eve, bandantonio, cbid2

🚥 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 clearly states the main change: adding unit tests for scripts/compose.ts.
Linked Issues check ✅ Passed The PR adds compose.ts Jest tests covering slug generation, front matter, file writing, and error handling, and refactors the script to make that testable.
Out of Scope Changes check ✅ Passed All code changes support the testing objective: the compose.ts refactor and Jest config update enable and measure the new unit tests.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
✨ 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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

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 (1)
scripts/compose.ts (1)

9-9: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Optional: prefer the node: protocol import.

SonarCloud flags import ... from 'url'; node:url makes the built-in explicit. Purely stylistic.

♻️ Proposed change
-import { fileURLToPath } from 'url';
+import { fileURLToPath } from 'node:url';
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@scripts/compose.ts` at line 9, Update the fileURLToPath import in
scripts/compose.ts to use the explicit node:url protocol instead of url. No
other changes are needed.

Source: Linters/SAST tools

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@scripts/compose.ts`:
- Around line 202-204: Return the Promise from writePost(answers) within the
.then callback so its rejection propagates to the existing .catch handler; do
not leave the asynchronous call unreturned.

---

Nitpick comments:
In `@scripts/compose.ts`:
- Line 9: Update the fileURLToPath import in scripts/compose.ts to use the
explicit node:url protocol instead of url. No other changes are needed.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 5d0986d7-3a40-4596-8d3e-79db12e92055

📥 Commits

Reviewing files that changed from the base of the PR and between 8d27330 and 29ad5ed.

📒 Files selected for processing (3)
  • jest.config.js
  • scripts/compose.ts
  • tests/scripts/compose.test.ts

Comment thread scripts/compose.ts
@codxbrexx

Copy link
Copy Markdown
Contributor Author

@princerajpoot20

I've added the missing scripts/compose.ts tests. Could you please review the PR and let me know if anything else needs to be changed or improved?

@princerajpoot20 princerajpoot20 left a comment

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.

@codxbrexx

What is the reason for making changes in the scripts folder when the objective was only to add tests? I was expecting the changes to be limited to the test files.

Also, Sonar has reported two issues. Please have a look at it.

…in, and improve error handling for CLI execution
@codxbrexx

Copy link
Copy Markdown
Contributor Author

@codxbrexx

What is the reason for making changes in the scripts folder when the objective was only to add tests? I was expecting the changes to be limited to the test files.

Also, Sonar has reported two issues. Please have a look at it.

The original file runs inquirer.prompt() at the top level, so Jest hangs the moment it imports the file — making it impossible to test.

The refactor wraps the CLI in main() with a process.argv guard (same pattern as build-meetings.ts), with zero change to runtime behavior. The tests cannot exist without it.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
scripts/compose.ts (2)

175-215: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Prefer try/catch over mixed async/await + .then/.catch.

main() is declared async but uses .then().catch() chaining instead of await with try/catch. This mixes two paradigms unnecessarily and reduces readability. Refactoring to pure async/await with try/catch is more idiomatic and easier to maintain.

♻️ Proposed refactor
 async function main(): Promise<void> {
-  await inquirer
-    .prompt([
+  try {
+    const answers = await inquirer.prompt([
       {
         name: 'title',
         message: 'Enter post title:',
         type: 'input'
       },
       {
         name: 'excerpt',
         message: 'Enter post excerpt:',
         type: 'input'
       },
       {
         name: 'tags',
         message: 'Any Tags? Separate them with , or leave empty if no tags.',
         type: 'input'
       },
       {
         name: 'type',
         message: 'Enter the post type:',
         type: 'list',
         choices: ['Communication', 'Community', 'Engineering', 'Marketing', 'Strategy', 'Video']
       },
       {
         name: 'canonical',
         message: 'Enter the canonical URL if any:',
         type: 'input'
       }
-    ])
-    .then((answers: ComposePromptType) => {
-      return writePost(answers);
-    })
-    .catch((error) => {
+    ]);
+    await writePost(answers);
+  } catch (error) {
       logger.error(error);
       if (error.isTtyError) {
         logger.error("Prompt couldn't be rendered in the current environment");
       } else {
         logger.error('Something went wrong, sorry!');
       }
-    });
+  }
 }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@scripts/compose.ts` around lines 175 - 215, Refactor main() to use a
try/catch around the awaited inquirer.prompt call, then pass the resulting
answers to writePost with await. Remove the chained .then() and .catch() calls
while preserving the existing logger.error handling, including the
isTtyError-specific message and fallback error message.

220-222: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Consider top-level await as an alternative to main().catch().

SonarCloud flags this line suggesting top-level await. Since the module already uses ESM (import.meta.url), top-level await is available and would simplify the entry-point error handling. This is optional — the current pattern is safe and widely used.

♻️ Optional refactor
-  main().catch((error) => {
-    logger.error(error);
-  });
+  try {
+    await main();
+  } catch (error) {
+    logger.error(error);
+  }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@scripts/compose.ts` around lines 220 - 222, Optionally replace the
main().catch entry-point in scripts/compose.ts with top-level await, preserving
the existing logger.error handling for failures. Since main is already the entry
function and the module uses ESM, keep behavior unchanged while simplifying the
error-handling flow.

Source: Linters/SAST tools

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@scripts/compose.ts`:
- Around line 175-215: Refactor main() to use a try/catch around the awaited
inquirer.prompt call, then pass the resulting answers to writePost with await.
Remove the chained .then() and .catch() calls while preserving the existing
logger.error handling, including the isTtyError-specific message and fallback
error message.
- Around line 220-222: Optionally replace the main().catch entry-point in
scripts/compose.ts with top-level await, preserving the existing logger.error
handling for failures. Since main is already the entry function and the module
uses ESM, keep behavior unchanged while simplifying the error-handling flow.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: aae553c0-3ad6-42c1-9924-d4335bf98c8d

📥 Commits

Reviewing files that changed from the base of the PR and between f36e487 and 937acfa.

📒 Files selected for processing (1)
  • scripts/compose.ts

@sonarqubecloud

Copy link
Copy Markdown

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

Projects

Status: To Be Triaged

Development

Successfully merging this pull request may close these issues.

[TEST]: Add unit tests for scripts/compose.ts

3 participants