Skip to content

Revise and expand block update tests #1120

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

medchedli
Copy link
Contributor

@medchedli medchedli commented Jun 11, 2025

Enhance the test coverage for block updates, including handling circular references and ensuring blocks are not updated if their references are not in the moved IDs.

Summary by CodeRabbit

  • Tests
    • Enhanced test coverage for block handling scenarios, including circular references and category updates.
    • Improved accuracy and consistency of test data and assertions.
    • Refined test logic to better reflect expected behaviors when updating blocks.

Copy link
Contributor

coderabbitai bot commented Jun 11, 2025

Walkthrough

The test suite for BlockRepository was updated with new and refined test cases, particularly for methods handling block updates within and outside category scopes. The changes include enhanced checks for circular references, improved mock setups, and more precise query expectations. All modifications are limited to the test file.

Changes

File(s) Change Summary
api/src/chat/repositories/block.repository.spec.ts Expanded and refined test cases for block update methods, improved mocks, added ObjectId usage.

Sequence Diagram(s)

sequenceDiagram
    participant TestSuite
    participant BlockRepository
    participant DB (Mocked)
    
    TestSuite->>BlockRepository: preUpdateMany(movedBlockIds)
    BlockRepository->>DB: find({ _id: { $in: movedBlockIds } })
    BlockRepository->>DB: find({ _id: { $nin: movedBlockIds }, nextBlocks: { $in: movedBlockIds } })
    BlockRepository->>BlockRepository: prepareBlocksInCategoryUpdateScope(...)
    BlockRepository->>BlockRepository: prepareBlocksOutOfCategoryUpdateScope(...)
    BlockRepository-->>TestSuite: (Assertions on update calls)
Loading

Possibly related PRs

Suggested labels

needs-review

Poem

A rabbit hops through lines of test,
Ensuring blocks behave their best.
With mocks and IDs, circles checked,
No sneaky bugs are left unchecked.
In code’s bright warren, tests now gleam—
Each block and link a perfect team! 🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@medchedli medchedli changed the base branch from main to fix/block-move-reference-cleanup June 12, 2025 07:49
@medchedli medchedli changed the base branch from fix/block-move-reference-cleanup to main June 12, 2025 07:49
@medchedli medchedli self-assigned this Jun 12, 2025
@medchedli medchedli marked this pull request as ready for review June 13, 2025 08:25
@medchedli
Copy link
Contributor Author

@coderabbitai review

Copy link
Contributor

coderabbitai bot commented Jun 13, 2025

✅ 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: 1

🧹 Nitpick comments (3)
api/src/chat/repositories/block.repository.spec.ts (3)

208-243: Circular-reference test passes but mock completeness can be improved

Solid scenario, but jest.spyOn(blockRepository, 'find') is left dangling without restoring the original implementation, which could leak into following tests if any of them rely on find’s real behaviour.
Add mockRestore() (or move the spy inside afterEach) to keep the suite isolated.

226   .mockResolvedValue({} as any);
+    // Ensure isolation
+    afterEach(() => {
+      (blockRepository.find as jest.Mock).mockRestore();
+    });

342-355: ObjectId strictness causes second find expectation to fail

preUpdateMany builds the second query with string IDs, whereas the test expects Types.ObjectId instances, leading to the pipeline failure at line 348.

Unless the production code converts to ObjectIds, replace the strict equality with a looser matcher:

-      expect(mockFind).toHaveBeenNthCalledWith(2, {
-        _id: { $nin: objectIds },
+      expect(mockFind).toHaveBeenNthCalledWith(2, {
+        _id: { $nin: validIds },
         category: movedBlocks[0].category,
         $or: [
-          { attachedBlock: { $in: objectIds } },
-          { nextBlocks: { $in: objectIds } },
+          { attachedBlock: { $in: validIds } },
+          { nextBlocks: { $in: validIds } },
         ],
       });

or use expect.arrayContaining to stay implementation-agnostic.
This will unblock the failing assertion without weakening coverage.

🧰 Tools
🪛 GitHub Actions: workflow 1837 of branch chore/add-unit-tests-for-blocks-category-updates

[error] 348-348: Test failure: Expected mockFind to have been called with specific arguments on the 2nd call, but received different arguments.


10-10: Unused Types import once expectations are loosened

If the previous comment is applied and you stop converting to ObjectId, the Types import becomes dead code – drop it to keep the spec tidy.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f7a981c and 3e1a20b.

📒 Files selected for processing (1)
  • api/src/chat/repositories/block.repository.spec.ts (5 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
api/src/chat/repositories/block.repository.spec.ts (1)
api/src/chat/repositories/block.repository.ts (2)
  • prepareBlocksInCategoryUpdateScope (171-194)
  • prepareBlocksOutOfCategoryUpdateScope (204-221)
🪛 GitHub Actions: workflow 1837 of branch chore/add-unit-tests-for-blocks-category-updates
api/src/chat/repositories/block.repository.spec.ts

[error] 306-306: Test failure: Expected mockUpdateOne not to have been called, but it was called once.


[error] 348-348: Test failure: Expected mockFind to have been called with specific arguments on the 2nd call, but received different arguments.

Comment on lines +287 to +307
it('should not update blocks if their references are not in the moved ids', async () => {
const otherBlocks = [
{
id: blockValidIds[1],
attachedBlock: 'some-other-id',
nextBlocks: [],
},
{
id: blockValidIds[2],
attachedBlock: null,
nextBlocks: ['some-other-id-2'],
},
] as Block[];
const mockUpdateOne = jest.spyOn(blockRepository, 'updateOne');

await blockRepository.prepareBlocksOutOfCategoryUpdateScope(otherBlocks, [
blockValidIds[0],
]);

expect(mockUpdateOne).not.toHaveBeenCalled();
});
Copy link
Contributor

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

⚠️ Potential issue

Failing assertion: implementation updates nextBlocks even when nothing changes

The pipeline error at line 306 stems from this expectation.
prepareBlocksOutOfCategoryUpdateScope currently performs

if (nextBlocks?.length) { updateOne(...) }

meaning it will always run updateOne when nextBlocks is non-empty – even if no element was removed.
Your test (correctly) assumes we should skip the write when the payload is identical.

Either:

  1. Change the repository implementation to avoid redundant writes (preferred):
- const nextBlocks = block.nextBlocks?.filter(
-   (nextBlock) => !ids.includes(nextBlock),
- );
-
- if (nextBlocks?.length) {
+ const filteredNextBlocks = block.nextBlocks?.filter(
+   (nextBlock) => !ids.includes(nextBlock),
+ );
+
+ if (
+   filteredNextBlocks &&
+   filteredNextBlocks.length !== block.nextBlocks.length
+ ) {
     await this.updateOne(block.id, { nextBlocks: filteredNextBlocks });
 }
  1. Or relax the expectation in this test to allow one call.

Choose 1 if you want to avoid unnecessary DB writes.

🧰 Tools
🪛 GitHub Actions: workflow 1837 of branch chore/add-unit-tests-for-blocks-category-updates

[error] 306-306: Test failure: Expected mockUpdateOne not to have been called, but it was called once.

🤖 Prompt for AI Agents
In api/src/chat/repositories/block.repository.spec.ts around lines 287 to 307,
the test expects no calls to updateOne when nextBlocks remain unchanged, but the
current implementation calls updateOne whenever nextBlocks is non-empty. To fix
this, modify the prepareBlocksOutOfCategoryUpdateScope method to compare the
existing nextBlocks with the new nextBlocks and only call updateOne if there is
an actual change, thereby preventing redundant database writes.

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.

🤔 [ISSUE] - NextBlocks links referencing to moved blocks are not removed
1 participant