Skip to content

fix(dataExport): Handle empty emails array TypeError#39186

Open
Harshit2405-2004 wants to merge 3 commits intoRocketChat:developfrom
Harshit2405-2004:fix/data-export-empty-emails-crash
Open

fix(dataExport): Handle empty emails array TypeError#39186
Harshit2405-2004 wants to merge 3 commits intoRocketChat:developfrom
Harshit2405-2004:fix/data-export-empty-emails-crash

Conversation

@Harshit2405-2004
Copy link

@Harshit2405-2004 Harshit2405-2004 commented Feb 28, 2026

Closes #39185.
Proposed Changes- Adds safe optional chaining to prevent Data Export emails .forEach loop crashing synchronously due to a TypeError if a user has an explicitly empty emails array.

Summary by CodeRabbit

  • Tests

    • Added automated tests for email export to verify recipient selection when some users lack emails, ensure the mailer is invoked once, and confirm no runtime errors during processing.
  • Bug Fixes

    • Made email extraction resilient to empty or missing email data to prevent crashes and allow the export loop to continue.

Closes RocketChat#39185

Adds safe optional chaining to user.emails[0].address in sendViaEmail.ts to prevent throwing TypeError when the array is explicitly empty.
@Harshit2405-2004 Harshit2405-2004 requested a review from a team as a code owner February 28, 2026 09:55
@dionisio-bot
Copy link
Contributor

dionisio-bot bot commented Feb 28, 2026

Looks like this PR is not ready to merge, because of the following issues:

  • This PR is missing the 'stat: QA assured' label
  • This PR is missing the required milestone or project

Please fix the issues and try again

If you have any trouble, please check the PR guidelines

@changeset-bot
Copy link

changeset-bot bot commented Feb 28, 2026

🦋 Changeset detected

Latest commit: 99fc95a

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 41 packages
Name Type
@rocket.chat/meteor Patch
@rocket.chat/core-typings Patch
@rocket.chat/rest-typings Patch
@rocket.chat/uikit-playground Patch
@rocket.chat/api-client Patch
@rocket.chat/apps Patch
@rocket.chat/core-services Patch
@rocket.chat/cron Patch
@rocket.chat/ddp-client Patch
@rocket.chat/fuselage-ui-kit Patch
@rocket.chat/gazzodown Patch
@rocket.chat/http-router Patch
@rocket.chat/livechat Patch
@rocket.chat/model-typings Patch
@rocket.chat/ui-avatar Patch
@rocket.chat/ui-client Patch
@rocket.chat/ui-contexts Patch
@rocket.chat/ui-voip Patch
@rocket.chat/web-ui-registration Patch
@rocket.chat/account-service Patch
@rocket.chat/authorization-service Patch
@rocket.chat/ddp-streamer Patch
@rocket.chat/omnichannel-transcript Patch
@rocket.chat/presence-service Patch
@rocket.chat/queue-worker Patch
@rocket.chat/abac Patch
@rocket.chat/federation-matrix Patch
@rocket.chat/license Patch
@rocket.chat/media-calls Patch
@rocket.chat/omnichannel-services Patch
@rocket.chat/pdf-worker Patch
@rocket.chat/presence Patch
rocketchat-services Patch
@rocket.chat/models Patch
@rocket.chat/network-broker Patch
@rocket.chat/omni-core-ee Patch
@rocket.chat/mock-providers Patch
@rocket.chat/ui-video-conf Patch
@rocket.chat/instance-status Patch
@rocket.chat/omni-core Patch
@rocket.chat/server-fetch Patch

Not sure what this means? Click here to learn what changesets are.

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

@CLAassistant
Copy link

CLAassistant commented Feb 28, 2026

CLA assistant check
All committers have signed the CLA.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 28, 2026

Walkthrough

Adds a unit test for sendViaEmail and fixes a TypeError by using safe optional chaining when reading a user's first email address, preventing crashes when a user's emails array is empty or undefined.

Changes

Cohort / File(s) Summary
Test specification
apps/meteor/server/lib/dataExport/sendViaEmail.spec.ts
New unit test that mocks models, mailer, settings, UI utils, and moment locale to verify sendViaEmail handles multiple users, skips users with empty/undefined emails without throwing, records missing users, and invokes mailer.send with correct recipients.
Implementation fix
apps/meteor/server/lib/dataExport/sendViaEmail.ts
Added safe optional chaining (emails?.[0]?.address) to avoid a TypeError when emails is an empty array or undefined; minor HTML template formatting adjusted only.
Changeset
.changeset/fix-data-export-crash.md
New changeset documenting a patch that prevents sendViaEmail from crashing when a user has an empty emails array.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The PR title 'fix(dataExport): Handle empty emails array TypeError' clearly and concisely describes the main change: fixing a TypeError crash caused by empty emails arrays in the data export functionality.
Linked Issues check ✅ Passed The PR addresses all coding requirements from #39185: adds optional chaining for safe email address access, prevents TypeError crashes, allows processing to continue when users have empty emails arrays, and includes a comprehensive unit test covering the edge case.
Out of Scope Changes check ✅ Passed All changes are directly related to fixing the issue: the sendViaEmail.ts modification adds safe optional chaining, the test file validates the fix, and the changeset documents the patch. No unrelated changes detected.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

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


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

@cubic-dev-ai cubic-dev-ai bot left a comment

Choose a reason for hiding this comment

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

No issues found across 2 files

Copy link
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.

🧹 Nitpick comments (2)
apps/meteor/server/lib/dataExport/sendViaEmail.spec.ts (2)

74-77: Remove inline comment per coding guidelines.

The comment on line 76 can be removed. The test name already communicates the intent, and the assertion pattern makes the expectation clear.

🧹 Proposed fix
         const executorUser = { _id: 'admin', username: 'admin', emails: [{ address: 'admin@example.com' }] };

-        // Should NOT throw TypeError
         const result = await sendViaEmail(reqData, executorUser as any);

As per coding guidelines: "Avoid code comments in the implementation"

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

In `@apps/meteor/server/lib/dataExport/sendViaEmail.spec.ts` around lines 74 - 77,
Remove the inline comment "// Should NOT throw TypeError" that sits immediately
before the invocation of sendViaEmail in the test; the test name and assertion
already communicate the expectation. Edit the test around the invocation of
sendViaEmail(reqData, executorUser as any) to delete that comment and leave the
executorUser and reqData setup and the result assignment intact.

37-57: mockMoment appears unused.

The mockMoment function defined on lines 37-41 is not referenced in the proxyquire setup. Instead, getMomentLocale is mocked directly. Consider removing mockMoment if it's not needed.

🧹 Proposed fix to remove unused code
-const mockMoment = function () {
-    return {
-        locale: () => ({ format: () => '12:00' }),
-    };
-};
-
 const { sendViaEmail } = proxyquire.load('./sendViaEmail.ts', {
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/meteor/server/lib/dataExport/sendViaEmail.spec.ts` around lines 37 - 57,
The mockMoment function declared as mockMoment is unused in this test — remove
its definition (the const mockMoment = function() { ... }) and any unused
imports related to it; if you intended to stub moment via the proxyquire.load
call for sendViaEmail, instead inject it by replacing the '../getMomentLocale'
stub with a module that returns mockMoment (i.e., ensure proxyquire.load for
'./sendViaEmail.ts' references getMomentLocale or delete mockMoment and leave
the current getMomentLocale stub as-is).
🤖 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/meteor/server/lib/dataExport/sendViaEmail.spec.ts`:
- Around line 74-77: Remove the inline comment "// Should NOT throw TypeError"
that sits immediately before the invocation of sendViaEmail in the test; the
test name and assertion already communicate the expectation. Edit the test
around the invocation of sendViaEmail(reqData, executorUser as any) to delete
that comment and leave the executorUser and reqData setup and the result
assignment intact.
- Around line 37-57: The mockMoment function declared as mockMoment is unused in
this test — remove its definition (the const mockMoment = function() { ... })
and any unused imports related to it; if you intended to stub moment via the
proxyquire.load call for sendViaEmail, instead inject it by replacing the
'../getMomentLocale' stub with a module that returns mockMoment (i.e., ensure
proxyquire.load for './sendViaEmail.ts' references getMomentLocale or delete
mockMoment and leave the current getMomentLocale stub as-is).

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between c6c71f0 and 19329c4.

📒 Files selected for processing (1)
  • apps/meteor/server/lib/dataExport/sendViaEmail.spec.ts
📜 Review details
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: cubic · AI code reviewer
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx,js}

📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)

**/*.{ts,tsx,js}: Write concise, technical TypeScript/JavaScript with accurate typing in Playwright tests
Avoid code comments in the implementation

Files:

  • apps/meteor/server/lib/dataExport/sendViaEmail.spec.ts
**/*.spec.ts

📄 CodeRabbit inference engine (.cursor/rules/playwright.mdc)

**/*.spec.ts: Use descriptive test names that clearly communicate expected behavior in Playwright tests
Use .spec.ts extension for test files (e.g., login.spec.ts)

Files:

  • apps/meteor/server/lib/dataExport/sendViaEmail.spec.ts
🧠 Learnings (15)
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : Ensure tests run reliably in parallel without shared state conflicts

Applied to files:

  • apps/meteor/server/lib/dataExport/sendViaEmail.spec.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : Group related tests in the same file

Applied to files:

  • apps/meteor/server/lib/dataExport/sendViaEmail.spec.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : All test files must be created in `apps/meteor/tests/e2e/` directory

Applied to files:

  • apps/meteor/server/lib/dataExport/sendViaEmail.spec.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : Utilize Playwright fixtures (`test`, `page`, `expect`) for consistency in test files

Applied to files:

  • apps/meteor/server/lib/dataExport/sendViaEmail.spec.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : Maintain test isolation between test cases in Playwright tests

Applied to files:

  • apps/meteor/server/lib/dataExport/sendViaEmail.spec.ts
📚 Learning: 2025-12-10T21:00:54.909Z
Learnt from: KevLehman
Repo: RocketChat/Rocket.Chat PR: 37091
File: ee/packages/abac/jest.config.ts:4-7
Timestamp: 2025-12-10T21:00:54.909Z
Learning: Rocket.Chat monorepo: Jest testMatch pattern '<rootDir>/src/**/*.spec.(ts|js|mjs)' is valid in this repo and used across multiple packages (e.g., packages/tools, ee/packages/omnichannel-services). Do not flag it as invalid in future reviews.

Applied to files:

  • apps/meteor/server/lib/dataExport/sendViaEmail.spec.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : Use `expect` matchers for assertions (`toEqual`, `toContain`, `toBeTruthy`, `toHaveLength`, etc.) instead of `assert` statements in Playwright tests

Applied to files:

  • apps/meteor/server/lib/dataExport/sendViaEmail.spec.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : Ensure clean state for each test execution in Playwright tests

Applied to files:

  • apps/meteor/server/lib/dataExport/sendViaEmail.spec.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to apps/meteor/tests/e2e/**/*.spec.ts : Use `test.step()` for complex test scenarios to improve organization in Playwright tests

Applied to files:

  • apps/meteor/server/lib/dataExport/sendViaEmail.spec.ts
📚 Learning: 2025-11-24T17:08:17.065Z
Learnt from: CR
Repo: RocketChat/Rocket.Chat PR: 0
File: .cursor/rules/playwright.mdc:0-0
Timestamp: 2025-11-24T17:08:17.065Z
Learning: Applies to **/*.spec.ts : Use descriptive test names that clearly communicate expected behavior in Playwright tests

Applied to files:

  • apps/meteor/server/lib/dataExport/sendViaEmail.spec.ts
📚 Learning: 2025-10-06T20:30:45.540Z
Learnt from: d-gubert
Repo: RocketChat/Rocket.Chat PR: 37152
File: packages/apps-engine/tests/test-data/storage/storage.ts:101-122
Timestamp: 2025-10-06T20:30:45.540Z
Learning: In `packages/apps-engine/tests/test-data/storage/storage.ts`, the stub methods (updatePartialAndReturnDocument, updateStatus, updateSetting, updateAppInfo, updateMarketplaceInfo) intentionally throw "Method not implemented." Tests using these methods must stub them using `SpyOn` from the test library rather than relying on actual implementations.

Applied to files:

  • apps/meteor/server/lib/dataExport/sendViaEmail.spec.ts
📚 Learning: 2025-12-16T17:29:45.163Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 37834
File: apps/meteor/tests/e2e/page-objects/fragments/admin-flextab-emoji.ts:12-22
Timestamp: 2025-12-16T17:29:45.163Z
Learning: In page object files under `apps/meteor/tests/e2e/page-objects/`, always import `expect` from `../../utils/test` (Playwright's async expect), not from Jest. Jest's `expect` has a synchronous signature and will cause TypeScript errors when used with web-first assertions like `toBeVisible()`.

Applied to files:

  • apps/meteor/server/lib/dataExport/sendViaEmail.spec.ts
📚 Learning: 2026-02-24T19:22:48.358Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 38493
File: apps/meteor/tests/e2e/omnichannel/omnichannel-send-pdf-transcript.spec.ts:66-67
Timestamp: 2026-02-24T19:22:48.358Z
Learning: In Playwright end-to-end tests (e.g., under apps/meteor/tests/e2e/...), prefer locating elements by translated text (getByText) and ARIA roles (getByRole) over data-qa attributes. If translation values change, update the corresponding test locators accordingly. Never use data-qa locators. This guideline applies to all Playwright e2e test specs in the repository and helps keep tests robust to UI text changes and accessible semantics.

Applied to files:

  • apps/meteor/server/lib/dataExport/sendViaEmail.spec.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In the Rocket.Chat repository, do not reference Biome lint rules in code review feedback. Biome is not used even if biome.json exists; only reference Biome rules if there is explicit, project-wide usage documented. For TypeScript files, review lint implications without Biome guidance unless the project enables Biome rules.

Applied to files:

  • apps/meteor/server/lib/dataExport/sendViaEmail.spec.ts
📚 Learning: 2026-02-26T19:25:44.063Z
Learnt from: gabriellsh
Repo: RocketChat/Rocket.Chat PR: 38778
File: packages/ui-voip/src/providers/useMediaSession.ts:192-192
Timestamp: 2026-02-26T19:25:44.063Z
Learning: In this repository (RocketChat/Rocket.Chat), Biome lint rules are not used even if a biome.json exists. When reviewing TypeScript files (e.g., packages/ui-voip/src/providers/useMediaSession.ts), ensure lint suggestions do not reference Biome-specific rules. Rely on general ESLint/TypeScript lint rules and project conventions instead.

Applied to files:

  • apps/meteor/server/lib/dataExport/sendViaEmail.spec.ts
🔇 Additional comments (6)
apps/meteor/server/lib/dataExport/sendViaEmail.spec.ts (6)

1-3: LGTM!

Appropriate testing library imports for a unit test with module isolation.


5-30: LGTM!

The mock correctly covers the three user email scenarios: valid email, empty array, and undefined. The cursor-like structure with toArray() appropriately mimics the model's return type.


32-35: LGTM!

Minimal and effective mailer mock with a stub that enables call verification.


37-41: LGTM!

Simple moment mock sufficient for dependency isolation.


59-62: LGTM!

Proper test isolation with beforeEach resetting stub history.


64-87: Well-structured test covering the edge case.

The test effectively validates that:

  1. Users with empty or undefined emails are correctly reported in missing
  2. Valid users are processed correctly
  3. The mailer is called with the combined recipient list

This directly addresses the PR objective of preventing TypeError when users have empty emails arrays.

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Backend [dataExport]: TypeError crash when user has empty emails array

2 participants