Skip to content

test: Added e2e api tests to loadSurroundingMessages method#39235

Closed
aleksandernsilva wants to merge 1 commit intodevelopfrom
test/load-surrounding-messages
Closed

test: Added e2e api tests to loadSurroundingMessages method#39235
aleksandernsilva wants to merge 1 commit intodevelopfrom
test/load-surrounding-messages

Conversation

@aleksandernsilva
Copy link
Contributor

@aleksandernsilva aleksandernsilva commented Mar 2, 2026

Proposed changes (including videos or screenshots)

This pull request adds a set of end-to-end tests for the loadSurroundingMessages Meteor method, ensuring its correct behavior under various scenarios. The tests cover authentication, parameter validation, and correct message retrieval, improving the robustness and reliability of the method.

This lays the groundwork to eventually deprecating the meteor method e re-implementing with a rest endpoint following our current best practices.

Issue(s)

CORE-1893

Steps to test or reproduce

N/A

Further comments

This PR relates to the fix being done for task CORE-1184 and PR #39092

Summary by CodeRabbit

  • Tests
    • Enhanced test coverage with additional test suite for message loading functionality.

Note: This release contains internal testing infrastructure improvements with no user-facing changes.

@dionisio-bot
Copy link
Contributor

dionisio-bot bot commented Mar 2, 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 Mar 2, 2026

⚠️ No Changeset found

Latest commit: 210dc87

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

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 2, 2026

Walkthrough

A test file was modified to add an import of sendMessage from chat.helper and to include a comprehensive test suite for loadSurroundingMessages functionality, though the test appears to be duplicated as two nearly identical describe blocks.

Changes

Cohort / File(s) Summary
Test API Methods
apps/meteor/tests/end-to-end/api/methods.ts
Added import of sendMessage helper. Added duplicate test suite for loadSurroundingMessages with setup, messaging sequence, and assertions appearing twice consecutively.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Suggested labels

type: chore

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Linked Issues check ⚠️ Warning The PR adds e2e tests for loadSurroundingMessages as required by CORE-1893 acceptance criteria, but the critical objectives of deprecating the Meteor method, implementing a REST endpoint, and updating RoomHistoryManager are not addressed in this PR. Complete the remaining CORE-1893 objectives: implement the REST endpoint, deprecate the Meteor method, and update RoomHistoryManager to consume the new endpoint before this PR can fully satisfy the linked issue requirements.
Out of Scope Changes check ⚠️ Warning The addition of a duplicate test suite appears to be unintended; the raw summary indicates two nearly identical describe blocks resulting in duplicated test logic, which is out of scope for adding e2e tests. Remove the duplicate test suite so that only a single, comprehensive loadSurroundingMessages test block remains, eliminating redundant test execution and reducing code duplication.
✅ 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 'test: Added e2e api tests to loadSurroundingMessages method' directly and clearly summarizes the main change: adding end-to-end API tests for the loadSurroundingMessages method.
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.


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.

@codecov
Copy link

codecov bot commented Mar 2, 2026

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 70.71%. Comparing base (3c30636) to head (210dc87).
⚠️ Report is 23 commits behind head on develop.

Additional details and impacted files

Impacted file tree graph

@@             Coverage Diff             @@
##           develop   #39235      +/-   ##
===========================================
- Coverage    70.76%   70.71%   -0.05%     
===========================================
  Files         3195     3195              
  Lines       113106   113106              
  Branches     20522    20497      -25     
===========================================
- Hits         80041    79986      -55     
- Misses       31018    31070      +52     
- Partials      2047     2050       +3     
Flag Coverage Δ
e2e 60.35% <ø> (-0.09%) ⬇️
e2e-api 47.95% <ø> (+0.10%) ⬆️
unit 71.36% <ø> (-0.07%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

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

@aleksandernsilva aleksandernsilva force-pushed the test/load-surrounding-messages branch from 3d561b7 to 210dc87 Compare March 2, 2026 02:42
@aleksandernsilva
Copy link
Contributor Author

@coderabbitai review

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Mar 2, 2026

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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.

Actionable comments posted: 2

🧹 Nitpick comments (1)
apps/meteor/tests/end-to-end/api/methods.ts (1)

3458-3475: Refactor repeated fixed sleeps into a small helper/constant.

Lines 3458-3475 repeat the same setTimeout(50) pattern several times. Extracting a helper (sleep) and a named delay constant will make this setup easier to maintain and tune.

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

In `@apps/meteor/tests/end-to-end/api/methods.ts` around lines 3458 - 3475,
Replace the repeated await new Promise(resolve => setTimeout(resolve, 50)) calls
with a small helper and constant: add a MESSAGE_DELAY_MS (or similar) constant
set to 50 and a sleep(ms: number) async helper (or sleep() that uses the
constant), then change each occurrence around the sendMessage calls (references:
sendMessage, middleMessage, threadMsg, tmid usage) to await sleep() or await
sleep(MESSAGE_DELAY_MS) so the delays are centralized and easily tunable.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/meteor/tests/end-to-end/api/methods.ts`:
- Around line 3630-3656: The test "should return messages in correct
chronological order" is currently disabled with xit; re-enable it and make it
resilient to flakiness by converting the arrow test to a function(done) and
enabling retries (e.g., call this.retries(3) at the top of the test body) so the
chronological ordering assertions inside the loadSurroundingMessages request
(see methodCall('loadSurroundingMessages') and the loop comparing
messages[i-1].ts.$date to messages[i].ts.$date) run reliably instead of being
skipped.
- Around line 3466-3473: Add a test that calls loadSurroundingMessages with a
thread message (reply) as the target to cover thread-target behavior: after
seeding thread data via sendMessage (the threadMsg variable and subsequent
replies), call loadSurroundingMessages using one of the reply messages' _id (or
the threadMsg.body.message._id) as the target and assert expected surrounding
messages/ordering/limits; duplicate the same shape for the other test region
that seeds threads (the block around the second thread seeding) so both places
exercise thread-target behavior. Ensure you reference sendMessage/threadMsg and
loadSurroundingMessages when adding the assertions so the new test targets the
thread reply ID.

---

Nitpick comments:
In `@apps/meteor/tests/end-to-end/api/methods.ts`:
- Around line 3458-3475: Replace the repeated await new Promise(resolve =>
setTimeout(resolve, 50)) calls with a small helper and constant: add a
MESSAGE_DELAY_MS (or similar) constant set to 50 and a sleep(ms: number) async
helper (or sleep() that uses the constant), then change each occurrence around
the sendMessage calls (references: sendMessage, middleMessage, threadMsg, tmid
usage) to await sleep() or await sleep(MESSAGE_DELAY_MS) so the delays are
centralized and easily tunable.

ℹ️ Review info

Configuration used: Organization UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3c30636 and 210dc87.

📒 Files selected for processing (1)
  • apps/meteor/tests/end-to-end/api/methods.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). (3)
  • GitHub Check: 📦 Build Packages
  • GitHub Check: CodeQL-Build
  • GitHub Check: CodeQL-Build
🧰 Additional context used
📓 Path-based instructions (1)
**/*.{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/tests/end-to-end/api/methods.ts
🧠 Learnings (12)
📓 Common learnings
Learnt from: ggazzo
Repo: RocketChat/Rocket.Chat PR: 35995
File: apps/meteor/app/api/server/v1/rooms.ts:1107-1112
Timestamp: 2026-02-23T17:53:18.785Z
Learning: In Rocket.Chat PR reviews, maintain strict scope boundaries—when a PR is focused on a specific endpoint (e.g., rooms.favorite), avoid reviewing or suggesting changes to other endpoints that were incidentally refactored (e.g., rooms.invite) unless explicitly requested by maintainers.
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 38493
File: apps/meteor/tests/e2e/page-objects/fragments/home-content.ts:60-82
Timestamp: 2026-02-24T19:36:55.089Z
Learning: In RocketChat/Rocket.Chat e2e tests (apps/meteor/tests/e2e/page-objects/fragments/home-content.ts), thread message preview listitems do not have aria-roledescription="message", so lastThreadMessagePreview locator cannot be scoped to messageListItems (which filters for aria-roledescription="message"). It should remain scoped to page.getByRole('listitem') or mainMessageList.getByRole('listitem').
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.
📚 Learning: 2026-02-24T19:16:35.307Z
Learnt from: sampaiodiego
Repo: RocketChat/Rocket.Chat PR: 39003
File: apps/meteor/client/lib/chats/flows/sendMessage.ts:39-45
Timestamp: 2026-02-24T19:16:35.307Z
Learning: In apps/meteor/client/lib/chats/flows/sendMessage.ts, when sdk.call('sendMessage', ...) throws an error, the message is intentionally left with temp: true (not deleted or cleaned up) to support a future retry UI feature. This allows users to retry sending failed messages rather than losing them.

Applied to files:

  • apps/meteor/tests/end-to-end/api/methods.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 tests run reliably in parallel without shared state conflicts

Applied to files:

  • apps/meteor/tests/end-to-end/api/methods.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/tests/end-to-end/api/methods.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/tests/end-to-end/api/methods.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/page-objects/**/*.ts : Utilize existing page objects pattern from `apps/meteor/tests/e2e/page-objects/`

Applied to files:

  • apps/meteor/tests/end-to-end/api/methods.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/tests/end-to-end/api/methods.ts
📚 Learning: 2026-02-25T20:10:16.987Z
Learnt from: ahmed-n-abdeltwab
Repo: RocketChat/Rocket.Chat PR: 38913
File: packages/ddp-client/src/legacy/types/SDKLegacy.ts:34-34
Timestamp: 2026-02-25T20:10:16.987Z
Learning: In the RocketChat/Rocket.Chat monorepo, packages/ddp-client and apps/meteor do not use TypeScript project references. Module augmentations in apps/meteor (e.g., declare module 'rocket.chat/rest-typings') are not visible when compiling packages/ddp-client in isolation, which is why legacy SDK methods that depend on OperationResult types for OpenAPI-migrated endpoints must remain commented out.

Applied to files:

  • apps/meteor/tests/end-to-end/api/methods.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/tests/end-to-end/api/methods.ts
📚 Learning: 2026-02-24T19:36:55.089Z
Learnt from: juliajforesti
Repo: RocketChat/Rocket.Chat PR: 38493
File: apps/meteor/tests/e2e/page-objects/fragments/home-content.ts:60-82
Timestamp: 2026-02-24T19:36:55.089Z
Learning: In RocketChat/Rocket.Chat e2e tests (apps/meteor/tests/e2e/page-objects/fragments/home-content.ts), thread message preview listitems do not have aria-roledescription="message", so lastThreadMessagePreview locator cannot be scoped to messageListItems (which filters for aria-roledescription="message"). It should remain scoped to page.getByRole('listitem') or mainMessageList.getByRole('listitem').

Applied to files:

  • apps/meteor/tests/end-to-end/api/methods.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/tests/end-to-end/api/methods.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/tests/end-to-end/api/methods.ts
🧬 Code graph analysis (1)
apps/meteor/tests/end-to-end/api/methods.ts (4)
packages/core-services/src/index.ts (1)
  • api (61-61)
apps/meteor/tests/data/rooms.helper.ts (1)
  • deleteRoom (98-99)
packages/ddp-client/src/legacy/RocketchatSDKLegacy.ts (1)
  • methodCall (186-188)
packages/livechat/src/lib/room.js (1)
  • messages (258-258)
🪛 Biome (2.4.4)
apps/meteor/tests/end-to-end/api/methods.ts

[error] 3455-3476: Duplicate before hook found.

(lint/suspicious/noDuplicateTestHooks)

🔇 Additional comments (1)
apps/meteor/tests/end-to-end/api/methods.ts (1)

9-9: Import change looks correct and is used.

sendMessage is consumed by the new [@loadSurroundingMessages] suite, so this addition is clean.

Comment on lines +3466 to +3473
const threadMsg = await sendMessage({ message: { rid, msg: 'Message 4 (Thread)' } });

await new Promise((resolve) => setTimeout(resolve, 50));
await sendMessage({ message: { rid, msg: 'Message 4.1 (Reply)', tmid: threadMsg.body.message._id } });

await new Promise((resolve) => setTimeout(resolve, 50));
await sendMessage({ message: { rid, msg: 'Message 4.2 (Reply)', tmid: threadMsg.body.message._id } });

Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Add a test where the target is a thread message/reply.

Line 3466 seeds thread data, but none of the assertions call loadSurroundingMessages with a thread message as the target. That leaves thread-target behavior unguarded for this method.

Suggested test shape
+		let threadReplyMessage: IMessage;
...
-			await sendMessage({ message: { rid, msg: 'Message 4.1 (Reply)', tmid: threadMsg.body.message._id } });
+			threadReplyMessage = (await sendMessage({ message: { rid, msg: 'Message 4.1 (Reply)', tmid: threadMsg.body.message._id } })).body.message;
...
+		it('should handle surrounding lookup when target is a thread reply', (done) => {
+			void request
+				.post(methodCall('loadSurroundingMessages'))
+				.set(credentials)
+				.send({
+					message: JSON.stringify({
+						method: 'loadSurroundingMessages',
+						params: [threadReplyMessage, 3],
+						id: 'id',
+						msg: 'method',
+					}),
+				})
+				.expect(200)
+				.expect((res) => {
+					const { result } = JSON.parse(res.body.message);
+					expect(result).to.have.property('messages').that.is.an('array');
+				})
+				.end(done);
+		});

Also applies to: 3584-3626

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

In `@apps/meteor/tests/end-to-end/api/methods.ts` around lines 3466 - 3473, Add a
test that calls loadSurroundingMessages with a thread message (reply) as the
target to cover thread-target behavior: after seeding thread data via
sendMessage (the threadMsg variable and subsequent replies), call
loadSurroundingMessages using one of the reply messages' _id (or the
threadMsg.body.message._id) as the target and assert expected surrounding
messages/ordering/limits; duplicate the same shape for the other test region
that seeds threads (the block around the second thread seeding) so both places
exercise thread-target behavior. Ensure you reference sendMessage/threadMsg and
loadSurroundingMessages when adding the assertions so the new test targets the
thread reply ID.

Comment on lines +3630 to +3656
xit('should return messages in correct chronological order', (done) => {
void request
.post(methodCall('loadSurroundingMessages'))
.set(credentials)
.send({
message: JSON.stringify({
method: 'loadSurroundingMessages',
params: [middleMessage, 50, false],
id: 'id',
msg: 'method',
}),
})
.expect('Content-Type', 'application/json')
.expect(200)
.expect((res) => {
const { result } = JSON.parse(res.body.message);
expect(result).to.have.property('messages').that.is.an('array');
const messages = result.messages as (IMessage & { ts: { $date: number } })[];

for (let i = 1; i < messages.length; i++) {
const currentTs = messages[i - 1].ts.$date;
const nextTs = messages[i].ts.$date;
expect(nextTs).to.be.greaterThan(currentTs);
}
})
.end(done);
});
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Do not leave ordering coverage skipped for this method.

The chronological-order check is currently xit, so ordering regressions can pass unnoticed. If it is flaky, gate it with retry instead of skipping entirely.

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

In `@apps/meteor/tests/end-to-end/api/methods.ts` around lines 3630 - 3656, The
test "should return messages in correct chronological order" is currently
disabled with xit; re-enable it and make it resilient to flakiness by converting
the arrow test to a function(done) and enabling retries (e.g., call
this.retries(3) at the top of the test body) so the chronological ordering
assertions inside the loadSurroundingMessages request (see
methodCall('loadSurroundingMessages') and the loop comparing
messages[i-1].ts.$date to messages[i].ts.$date) run reliably instead of being
skipped.

@aleksandernsilva
Copy link
Contributor Author

Closed in favor of #39291

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.

1 participant