Skip to content

Feature/unit tests for integrations#620

Merged
lukasz-hycom merged 20 commits intomainfrom
feature/unit-tests-for-integrations
Feb 4, 2026
Merged

Feature/unit tests for integrations#620
lukasz-hycom merged 20 commits intomainfrom
feature/unit-tests-for-integrations

Conversation

@lukasz-hycom
Copy link
Copy Markdown
Contributor

@lukasz-hycom lukasz-hycom commented Feb 2, 2026

What does this PR do?

Key Changes

  • Testing for the integration packages was extended to cover the key service and mapper layers for Contentful, Strapi, Algolia, Medusa, Redis, and Zendesk. The new tests verify client configuration (URLs, headers, tokens), request/response mapping, error handling, and delegation to the generated SDKs or HTTP clients

Summary by CodeRabbit

  • Tests

    • Added extensive unit tests across multiple integrations (Algolia, Zendesk, Redis, MedusaJS, Contentful, Strapi) covering services, mappers, and error handling.
  • Bug Fixes

    • Service list totals now reflect upstream counts.
    • Cache retrieval consistently returns undefined when empty.
  • Chores

    • Standardized Vitest configuration and added coverage collection, merging, and reporting automation.
    • Updated ignore rules and added a report-view script.

@vercel
Copy link
Copy Markdown

vercel Bot commented Feb 2, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
o2s-docs Skipped Skipped Feb 4, 2026 2:40pm

Request Review

@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented Feb 2, 2026

Walkthrough

This PR adds Vitest-based test suites across many integrations, per-package Vitest configs, coverage collection/merge/report tooling and CI steps, enables Vitest coverage reporting, updates several package.json test/devDependencies, and adds four .gitignore entries and small code/test tweaks.

Changes

Cohort / File(s) Summary
Git Configuration
\.gitignore
Ignore agent-os, AGENTS.md, CLAUDE.md, and .claude.
Root Config & Scripts
package.json, vitest.config.ts
Added view-report script and enabled Vitest coverage (v8 provider, text-summary/html/json-summary/json reporters).
Shared Vitest Config & Coverage Tooling
packages/configs/vitest-config/api.js, packages/configs/vitest-config/block.js, packages/configs/vitest-config/package.json, packages/configs/vitest-config/scripts/collect-json-outputs.mjs, packages/configs/vitest-config/scripts/merge-summary-outputs.mjs, packages/configs/vitest-config/turbo.json
Added coverage config, npm scripts for collecting/merging/reporting coverage, Turbo tasks, and scripts to collect and merge coverage summaries.
CI Test Action
.github/actions/test/action.yaml
Appended conditional steps to detect/collect/merge/report/upload Vitest coverage artifacts and added a Vitest coverage report action guarded by a has_coverage check.
Algolia Integration
packages/integrations/algolia/package.json, packages/integrations/algolia/vitest.config.mjs, packages/integrations/algolia/src/modules/search/mappers/articles.mapper.ts, packages/integrations/algolia/src/modules/search/mappers/articles.mapper.spec.ts, packages/integrations/algolia/src/modules/search/search.service.spec.ts
Added test script & per-package Vitest config, removed a TODO comment, and added mapper and search service tests.
Zendesk Integration
packages/integrations/zendesk/package.json, packages/integrations/zendesk/vitest.config.mjs, packages/integrations/zendesk/src/modules/tickets/zendesk-field.mapper.spec.ts, packages/integrations/zendesk/src/modules/tickets/zendesk-ticket.mapper.spec.ts, packages/integrations/zendesk/src/modules/tickets/zendesk-ticket.service.spec.ts
Added test script & Vitest config and comprehensive tests for field mapping, ticket mapping, and ticket service behavior.
Redis Integration
packages/integrations/redis/package.json, packages/integrations/redis/vitest.config.mjs, packages/integrations/redis/src/modules/cache/cache.service.ts, packages/integrations/redis/src/modules/cache/cache.service.spec.ts
Added test script & Vitest config, small change to cache.get return using nullish coalescing, and extensive cache service tests.
MedusaJS Integration
packages/integrations/medusajs/package.json, packages/integrations/medusajs/vitest.config.mjs, packages/integrations/medusajs/src/modules/...
Added test script & Vitest config with alias, numerous unit tests for services/mappers/resources, adjusted mapServices total to prefer data.count, and minor error message punctuation change.
Contentful CMS Integration
packages/integrations/contentful-cms/package.json, packages/integrations/contentful-cms/vitest.config.mjs, packages/integrations/contentful-cms/src/modules/graphql/graphql.service.spec.ts, packages/integrations/contentful-cms/src/modules/rest-delivery/delivery.service.spec.ts
Added test script & Vitest config with aliases, and tests for GraphQL and delivery services.
Strapi CMS Integration
packages/integrations/strapi-cms/package.json, packages/integrations/strapi-cms/vitest.config.mjs, packages/integrations/strapi-cms/src/modules/graphql/graphql.service.spec.ts
Added test script & Vitest config with aliases, and GraphQL service tests.
Per-package Vitest entrypoints
packages/integrations/*/vitest.config.mjs (algolia, zendesk, redis, medusajs, contentful-cms, strapi-cms)
New per-package Vitest configs that re-export or merge the shared config and set package-specific aliases.
Changeset
\.changeset/gold-dragons-thank.md
Added changeset documenting minor version bumps for multiple integration packages.

Sequence Diagram(s)

(omitted — changes are primarily tests, config, and CI steps)

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~50 minutes

Possibly related PRs

Suggested reviewers

  • marcinkrasowski

Poem

🐰 Nose twitch, paws at keys,
Tests sprout up beneath the trees.
Coverage cartwheels, colors bright,
Vitest hums through day and night.
Hoppity code—everything's alright. 🥕

🚥 Pre-merge checks | ✅ 1 | ❌ 2
❌ Failed checks (2 warnings)
Check name Status Explanation Resolution
Description check ⚠️ Warning The PR description is incomplete. It only covers 'Key Changes' but omits required sections: 'What does this PR do?', 'Related Ticket(s)', and 'How to test'. Add missing sections: explicitly state what the PR addresses (bugfix/feature), reference any related tickets, and provide detailed testing instructions including setup and step-by-step verification steps.
Docstring Coverage ⚠️ Warning Docstring coverage is 11.11% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (1 passed)
Check name Status Explanation
Title check ✅ Passed The title 'Feature/unit tests for integrations' clearly and specifically describes the main change: adding unit tests across multiple integration packages.

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

✨ Finishing touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feature/unit-tests-for-integrations

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.

@vercel vercel Bot temporarily deployed to Preview – o2s-docs February 2, 2026 14:57 Inactive
Comment thread packages/configs/vitest-config/scripts/collect-json-outputs.mjs Dismissed
@github-actions
Copy link
Copy Markdown
Contributor

github-actions Bot commented Feb 2, 2026

Coverage Report for packages/configs/vitest-config

Status Category Percentage Covered / Total
🔵 Lines 82.12% 698 / 850
🔵 Statements 81.97% 732 / 893
🔵 Functions 78.59% 257 / 327
🔵 Branches 72.65% 595 / 819
File Coverage
File Stmts Branches Functions Lines Uncovered Lines
Changed Files
packages/integrations/algolia/src/modules/search/mappers/articles.mapper.ts 100% 100% 100% 100%
packages/integrations/medusajs/src/modules/resources/resources.mapper.ts 90.62% 58.82% 92.3% 89.65% 82, 109-111
packages/integrations/medusajs/src/modules/resources/resources.service.ts 44.68% 55.55% 40.74% 44.68% 76, 102, 143-242
packages/integrations/redis/src/modules/cache/cache.service.ts 80.76% 94.44% 50% 80.76% 28, 34-39, 43-48, 52-57, 67-72
Generated in workflow #209 for commit 2a14738 by the Vitest Coverage Report Action

Comment thread packages/configs/vitest-config/scripts/collect-json-outputs.mjs Fixed
Copy link
Copy Markdown
Contributor

@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: 3

🤖 Fix all issues with AI agents
In @.github/actions/test/action.yaml:
- Around line 80-88: The workflow step using
davelosert/vitest-coverage-report-action@v2 includes unsupported inputs; remove
the unsupported keys "working-directory" and "vite-config-path" from the Vitest
coverage step and keep only the supported parameters (e.g., "json-summary-path",
"json-final-path", and "github-token") in the step configuration; if you must
adjust working directory or Vite config, consult the action's action.yml/README
for the correct option names or move that configuration into the Vitest config
file instead.

In `@packages/configs/vitest-config/package.json`:
- Around line 10-22: Add tsx to this package's devDependencies and make glob
versioning consistent with the other devDependencies: in package.json ensure the
"collect-json-reports" script (uses tsx) has a corresponding devDependency entry
for "tsx" and change "glob": "13.0.0" to use caret range "glob": "^13.0.0" so it
matches the caret style used by nyc/open-cli/vitest; update the devDependencies
block accordingly.

In `@packages/configs/vitest-config/turbo.json`:
- Around line 12-16: The "report" task's inputs path is incorrect: update the
"report" task (the report object) to use the merged coverage glob that matches
the "merge-json-reports" output (change inputs from "coverage/merge" to
"coverage/merged/**") so the report task correctly consumes the merged coverage
files.
🧹 Nitpick comments (3)
packages/configs/vitest-config/scripts/collect-json-outputs.mjs (2)

87-92: Incomplete multi-character sanitization (CodeQL finding).

The replaceDotPatterns function only performs a single-pass replacement. Input like ....// would become ../ after replacement. While this is only used for console logging (not file operations) and poses no security risk here, it could produce confusing output.

🔧 Proposed fix for complete sanitization
-        const replaceDotPatterns = (str) => str.replace(/\.\.\//g, '');
+        const replaceDotPatterns = (str) => {
+            let result = str;
+            while (result.includes('../')) {
+                result = result.replace(/\.\.\//g, '');
+            }
+            return result;
+        };

96-98: Add error handling for JSON parsing.

If a coverage-summary.json file is malformed, JSON.parse will throw and be caught by the outer try-catch, causing the entire collection to fail. Consider handling parse errors per-file to allow partial success.

🔧 Proposed fix with per-file error handling
         if (summaryFiles.length > 0) {
             const summaries = await Promise.all(
-                summaryFiles.map((p) => fs.readFile(p, 'utf8').then(JSON.parse)),
+                summaryFiles.map((p) =>
+                    fs.readFile(p, 'utf8')
+                        .then(JSON.parse)
+                        .catch((err) => {
+                            console.warn(`Warning: Failed to parse ${p}: ${err.message}`);
+                            return null;
+                        })
+                ),
             );
-            const merged = { total: aggregateTotals(summaries) };
+            const validSummaries = summaries.filter(Boolean);
+            const merged = { total: aggregateTotals(validSummaries) };
.github/actions/test/action.yaml (1)

48-50: Consider adding error handling for the collect step.

If collect-json-reports fails (e.g., no coverage data exists yet), the workflow will fail before the coverage check can determine whether to proceed. Adding continue-on-error: true would allow the subsequent check step to gracefully handle the absence of coverage.

♻️ Proposed fix
         - name: Collect coverage
           shell: bash
+          continue-on-error: true
           run: npx turbo run collect-json-reports --filter=@o2s/vitest-config

Comment thread .github/actions/test/action.yaml
Comment thread packages/configs/vitest-config/package.json
Comment thread packages/configs/vitest-config/turbo.json
@vercel vercel Bot temporarily deployed to Preview – o2s-docs February 3, 2026 07:25 Inactive
Copy link
Copy Markdown
Contributor

@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
`@packages/integrations/medusajs/src/modules/resources/resources.mapper.spec.ts`:
- Around line 106-121: The test reveals mapServices returns the filtered array
length as total; update mapServices so its returned total uses the original
server-side count (data.count) instead of services.length to match mapAssets
behavior; locate the mapServices function and replace the total assignment that
references services.length with data.count so pagination reflects the server
total even when items are filtered.
🧹 Nitpick comments (4)
packages/integrations/medusajs/src/modules/resources/resources.service.spec.ts (2)

57-57: Consider using vi.clearAllMocks() instead of vi.restoreAllMocks().

vi.restoreAllMocks() is intended for restoring spied implementations to their original state. Since this test uses vi.fn() mocks rather than vi.spyOn(), vi.clearAllMocks() would be more semantically appropriate for resetting mock call history between tests.

Suggested change
     beforeEach(() => {
-        vi.restoreAllMocks();
+        vi.clearAllMocks();
         mockHttpClient = { get: vi.fn() };

81-91: Standardize error messages in service implementation.

The error messages thrown by purchaseOrActivateResource (line 45: 'Method not implemented') and purchaseOrActivateService (line 49: 'Method not implemented.') are inconsistent—one lacks a trailing period while the other includes one. The tests correctly match these implementations, but the service methods should use consistent error messaging. Choose a single format and apply it to both methods.

packages/integrations/medusajs/src/modules/products/products.service.spec.ts (1)

113-120: Consider moving throwError import to file level.

The dynamic import of throwError inside the test is functional but unconventional. Moving it to the top-level imports alongside of would be cleaner.

♻️ Suggested refactor
-import { firstValueFrom, of } from 'rxjs';
+import { firstValueFrom, of, throwError } from 'rxjs';

Then simplify the test:

 it('should throw NotFoundException when HTTP returns 404', async () => {
-    const { throwError } = await import('rxjs');
     mockHttpClient.get.mockReturnValue(throwError(() => ({ status: 404 })));
packages/integrations/medusajs/src/modules/medusajs/medusajs.service.spec.ts (1)

9-13: Simplify the mock implementation.

The this: unknown type annotation and function syntax are unnecessary since the mock simply returns mockSdk without using this.

♻️ Suggested simplification
 vi.mock('@medusajs/js-sdk', () => ({
-    default: vi.fn().mockImplementation(function (this: unknown) {
-        return mockSdk;
-    }),
+    default: vi.fn(() => mockSdk),
 }));

Copy link
Copy Markdown
Contributor

@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 `@packages/configs/vitest-config/scripts/collect-json-outputs.mjs`:
- Around line 40-53: The current use of path.basename(match) (assigned to
directoryName) causes collisions when different packages/apps share the same
directory name; change the naming to a unique identifier by computing the
relative path from the repository root (e.g., path.relative(process.cwd(),
match)) and normalize it into a safe filename (replace path separators with
underscores or URL-encode) and use that value instead of directoryName when
building destinationFile and summaryDestinationFile so copies to rawFinalDir and
rawSummaryDir cannot overwrite each other; update all references that create
`${directoryName}.json` (the coverageFilePath copy and the COVERAGE_SUMMARY_PATH
handling) to use the new unique name.

Comment thread packages/configs/vitest-config/scripts/collect-json-outputs.mjs
@vercel vercel Bot temporarily deployed to Preview – o2s-docs February 3, 2026 14:13 Inactive
Copy link
Copy Markdown
Contributor

@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 `@packages/integrations/strapi-cms/src/modules/graphql/graphql.service.ts`:
- Line 21: The import at the end of
packages/integrations/strapi-cms/src/modules/graphql/graphql.service.ts was
changed to a relative path; revert it to the project alias used everywhere else
by importing from "@/generated/strapi" instead of the relative
'../../../generated/strapi' so graphql.service.ts matches the other files (e.g.,
cms.table.mapper.ts, cms.service.ts) and stays consistent with the codebase's
alias resolution.
🧹 Nitpick comments (2)
packages/integrations/contentful-cms/src/modules/rest-delivery/delivery.service.spec.ts (1)

103-111: Consider a more appropriate type assertion than as never.

The as never cast is unconventional here since never typically represents an impossible type. A clearer approach would be to use an explicit partial type or as any.

♻️ Suggested improvement
         it('should return empty array when items is undefined', async () => {
-            mockClient.getLocales.mockResolvedValue({} as never);
+            mockClient.getLocales.mockResolvedValue({} as { items?: undefined });

             const service = new RestDeliveryService(mockConfig as unknown as ConfigService);
packages/integrations/contentful-cms/src/modules/graphql/graphql.service.spec.ts (1)

32-59: Consider using vi.clearAllMocks() instead of vi.restoreAllMocks().

vi.restoreAllMocks() restores mocks to their original implementations, which can interfere with module-level vi.mock() calls. While the current code works because mockReset() and mockImplementationOnce() are called afterward, using vi.clearAllMocks() would be clearer since it only clears call history without affecting the mock implementations.

♻️ Suggested change
     beforeEach(() => {
-        vi.restoreAllMocks();
+        vi.clearAllMocks();
         process.env = { ...originalEnv };

Comment thread packages/integrations/strapi-cms/src/modules/graphql/graphql.service.ts Outdated
@vercel vercel Bot temporarily deployed to Preview – o2s-docs February 4, 2026 08:20 Inactive
@vercel vercel Bot temporarily deployed to Preview – o2s-docs February 4, 2026 14:40 Inactive
@lukasz-hycom lukasz-hycom merged commit 20a5bdd into main Feb 4, 2026
13 checks passed
@lukasz-hycom lukasz-hycom deleted the feature/unit-tests-for-integrations branch February 4, 2026 15:03
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