Skip to content

🧪 add unit tests for agency/server blog controller#15

Open
Adityavanjre wants to merge 5 commits into
mainfrom
test/agency-server-blog-controller-6964327158673213702
Open

🧪 add unit tests for agency/server blog controller#15
Adityavanjre wants to merge 5 commits into
mainfrom
test/agency-server-blog-controller-6964327158673213702

Conversation

@Adityavanjre

@Adityavanjre Adityavanjre commented May 8, 2026

Copy link
Copy Markdown
Owner

🎯 What: Missing tests for agency/server/controllers/blogController.js were added.
📊 Coverage: Covered successful retrieval, ID/slug lookup, creation, update, deletion, error statuses (400, 404, 500) and draft status checks logic for getBlogs, getBlogById, createBlog, updateBlog, and deleteBlog.
Result: Improved test coverage for the agency blog feature, ensuring robust code reliability and preventing regressions in endpoint behavior.


PR created automatically by Jules for task 6964327158673213702 started by @Adityavanjre

Summary by CodeRabbit

  • Bug Fixes

    • Prevented potential crashes when processing certain API responses and fixed a missing React hook import.
  • Tests

    • Added comprehensive tests for blog management with role-based checks and error/validation handling.
  • Chores

    • Updated development dependencies and project configuration; added npm scripts for development and testing.

Review Change Stack

Added a Jest unit test suite covering all endpoints (`getBlogs`, `getBlogById`, `createBlog`, `updateBlog`, `deleteBlog`) in `agency/server/controllers/blogController.js`. The test isolates logic by mocking Express requests/responses and the Mongoose Blog model. Also added Jest as a devDependency in agency/server/package.json.

Co-authored-by: Adityavanjre <66417028+Adityavanjre@users.noreply.github.com>
@google-labs-jules

Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@coderabbitai

coderabbitai Bot commented May 8, 2026

Copy link
Copy Markdown

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: 0f992f2e-7df8-4e45-b9e8-060ea34053cb

📥 Commits

Reviewing files that changed from the base of the PR and between 352086d and 344ad08.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (1)
  • agency/server/package.json

📝 Walkthrough

Walkthrough

This PR adds Jest tests for the blog controller (CRUD, role-based filters, slug/ID lookup, and error paths), adds test scripts and devDependencies to the server package, fixes a missing React hook import and a response-header type guard in the frontend, and updates root package devDependencies and the ajv override scoping.

Changes

Testing, Frontend Fixes, and Configuration

Layer / File(s) Summary
Blog Controller Test Suite and Test Infrastructure
agency/server/controllers/__tests__/blogController.test.js, agency/server/package.json
Comprehensive Jest tests for getBlogs, getBlogById, createBlog, updateBlog, deleteBlog with mocked Blog model, role-based filtering, slug-vs-ID lookup, and error cases (400/404/500). Adds test script and test-related devDependencies to the server package.
Frontend Bug Fixes
nexus/frontend/src/app/(dashboard)/manufacturing/machines/page.tsx, nexus/frontend/src/lib/api.ts
Adds missing useCallback import to machines page; adds a runtime check that response.headers['content-type'] is a string before calling includes().
Root Package Configuration and Dependencies
package.json
Expands/reorders root devDependencies with testing/lint tooling (jest, mockingoose, supertest, eslint-visitor-keys); reorders some dependencies entries; moves ajv override to be scoped under @nestjs/cli (@nestjs/cli.ajv: ^8.17.1).

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

🚥 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 pull request title directly references the main focus of the changeset: adding unit tests for the agency/server blog controller, which is the primary objective of the PR.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch test/agency-server-blog-controller-6964327158673213702
⚔️ Resolve merge conflicts
  • Resolve merge conflict in branch test/agency-server-blog-controller-6964327158673213702

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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 14836b8c10

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread agency/server/package.json
Added a Jest unit test suite covering all endpoints (`getBlogs`, `getBlogById`, `createBlog`, `updateBlog`, `deleteBlog`) in `agency/server/controllers/blogController.js`. The test isolates logic by mocking Express requests/responses and the Mongoose Blog model. Also added Jest as a devDependency in agency/server/package.json.

Fixed CI issue by upgrading `ajv` version from `^6.12.6` to `^8.17.1` in the root `package.json` overrides to resolve a module not found error in `@nestjs/cli` when generating Prisma client and building the application.

Co-authored-by: Adityavanjre <66417028+Adityavanjre@users.noreply.github.com>
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

google-labs-jules Bot and others added 2 commits May 8, 2026 06:59
Added a Jest unit test suite covering all endpoints (`getBlogs`, `getBlogById`, `createBlog`, `updateBlog`, `deleteBlog`) in `agency/server/controllers/blogController.js`. The test isolates logic by mocking Express requests/responses and the Mongoose Blog model. Also added Jest as a devDependency in agency/server/package.json.

Fixed CI issue by upgrading `ajv` version from `^6.12.6` to `^8.17.1` in the root `package.json` overrides to resolve a module not found error in `@nestjs/cli` when generating Prisma client and building the application.
Fixed `nexus/frontend` typescript errors in `src/app/(dashboard)/manufacturing/machines/page.tsx` and `src/lib/api.ts` which were causing the build step to fail.

Co-authored-by: Adityavanjre <66417028+Adityavanjre@users.noreply.github.com>
Added a Jest unit test suite covering all endpoints (`getBlogs`, `getBlogById`, `createBlog`, `updateBlog`, `deleteBlog`) in `agency/server/controllers/blogController.js`. The test isolates logic by mocking Express requests/responses and the Mongoose Blog model. Also added Jest as a devDependency in agency/server/package.json.

Fixed CI issue by upgrading `ajv` version from `^6.12.6` to `^8.17.1` in the root `package.json` overrides specifically for `@nestjs/cli` to resolve a module not found error when generating Prisma client and building the application, while retaining old `ajv` mapping for ESLint to prevent rule meta mapping errors.

Fixed `nexus/frontend` typescript errors in `src/app/(dashboard)/manufacturing/machines/page.tsx` and `src/lib/api.ts` which were causing the build step to fail.

Co-authored-by: Adityavanjre <66417028+Adityavanjre@users.noreply.github.com>
@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, you can upgrade your account or add credits to your account and enable them for code reviews in your settings.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

🧹 Nitpick comments (5)
agency/server/package.json (1)

26-31: 💤 Low value

Consider whether mongodb-memory-server and supertest are needed yet.

mongodb-memory-server and supertest are added as dev dependencies but are not imported or used in the test file included in this PR. The current tests use Jest mocks instead of spinning up an in-memory database or making HTTP requests.

If these packages are intended for future integration tests or used by other test files not shown in this PR, they're fine to keep. Otherwise, consider adding them when they're actually needed to keep dependencies lean.

🤖 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 `@agency/server/package.json` around lines 26 - 31, The package.json currently
includes devDependencies "mongodb-memory-server" and "supertest" which aren't
used by the tests in this PR; either remove these two packages from the
"devDependencies" block to keep dependencies minimal or, if you plan to add
integration tests, add a short comment in package.json or the test suite
referencing their intended use (mongodb-memory-server for in-memory MongoDB in
integration tests and supertest for HTTP endpoint testing) so future reviewers
know they are deliberate; update the "devDependencies" object (the entries
"mongodb-memory-server" and "supertest") accordingly.
agency/server/controllers/__tests__/blogController.test.js (3)

194-203: ⚡ Quick win

Inconsistent error status: updateBlog returns 400 for database errors.

The test expects 400 (client error) when Blog.findById rejects (line 201), but database/lookup failures typically warrant 500 (server error). This is inconsistent with the deleteBlog test at lines 232-241, which correctly returns 500 for the same scenario.

If the controller implementation returns 400 for all errors in updateBlog, consider aligning it with deleteBlog to return 500 for database errors and reserve 400 for validation errors (e.g., from save()).

♻️ Suggested correction
-        it('should handle 400 error', async () => {
+        it('should handle 500 error', async () => {
             req.params.id = 'some-id';
             const error = new Error('Update error');
             Blog.findById.mockRejectedValue(error);
 
             await updateBlog(req, res);
 
-            expect(res.status).toHaveBeenCalledWith(400);
+            expect(res.status).toHaveBeenCalledWith(500);
             expect(res.json).toHaveBeenCalledWith({ message: error.message });
         });
🤖 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 `@agency/server/controllers/__tests__/blogController.test.js` around lines 194
- 203, The test and controller are inconsistent: change updateBlog's error
handling to mirror deleteBlog by treating database/lookup rejections (e.g.,
errors thrown from Blog.findById) as server errors (status 500) while reserving
400 only for validation/save errors; update the updateBlog controller to catch
rejections from Blog.findById and respond with res.status(500).json({ message:
err.message }) (keep validation error handling for save() as 400) and then
adjust the test expectation in blogController.test.js to expect 500 for the
Blog.findById rejection case.

133-144: ⚡ Quick win

Consider simplifying the constructor assertion.

The assertion explicitly checks for undefined fields (lines 137-143), which tests implementation details rather than behavior. If the controller changes to omit undefined fields (e.g., using a spread of only defined values), this test will fail even though the behavior is equivalent.

♻️ Suggested simplification
         expect(Blog).toHaveBeenCalledWith({
             title: 'New Blog',
             author: 'John Doe',
             category: 'Tech',
-            image: undefined,
-            excerpt: undefined,
-            content: undefined,
-            readTime: undefined,
-            tags: undefined,
-            slug: undefined,
             status: 'published'
         });
+        // Or use expect.objectContaining() to check only required fields:
+        expect(Blog).toHaveBeenCalledWith(
+            expect.objectContaining({
+                title: 'New Blog',
+                author: 'John Doe',
+                category: 'Tech',
+                status: 'published'
+            })
+        );
🤖 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 `@agency/server/controllers/__tests__/blogController.test.js` around lines 133
- 144, The test currently asserts Blog was called with an object that includes
many explicit undefined fields which couples the test to implementation details;
update the assertion in blogController.test.js to only assert the important
properties (e.g., title, author, category, status) using a partial matcher like
expect.objectContaining({ title: 'New Blog', author: 'John Doe', category:
'Tech', status: 'published' }) when calling Blog, so it no longer requires
unspecified fields (leave Blog and the test around it intact, just replace the
full literal with an objectContaining matcher).

57-65: ⚡ Quick win

Consider using async rejection instead of synchronous throw.

Line 59 uses a synchronous throw, while other error tests (e.g., line 106, line 197) use mockRejectedValue() for async rejection. If the controller uses await Blog.find()..., a synchronous throw occurs before the await and requires different error handling than a promise rejection.

For consistency and to better match async/await patterns, consider:

♻️ Suggested async error pattern
-        it('should handle 500 error', async () => {
-            const error = new Error('Database error');
-            Blog.find.mockImplementation(() => { throw error; });
-
-            await getBlogs(req, res);
-
-            expect(res.status).toHaveBeenCalledWith(500);
-            expect(res.json).toHaveBeenCalledWith({ message: error.message });
-        });
+        it('should handle 500 error', async () => {
+            const error = new Error('Database error');
+            const mockSort = jest.fn().mockRejectedValue(error);
+            Blog.find.mockReturnValue({ sort: mockSort });
+
+            await getBlogs(req, res);
+
+            expect(res.status).toHaveBeenCalledWith(500);
+            expect(res.json).toHaveBeenCalledWith({ message: error.message });
+        });
🤖 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 `@agency/server/controllers/__tests__/blogController.test.js` around lines 57 -
65, The test for getBlogs uses a synchronous throw from Blog.find which doesn't
mimic an async rejection; change the mock to reject the promise (use
Blog.find.mockRejectedValue(error) or mockImplementation returning
Promise.reject(error)) so it matches the controller's await/async path and keeps
consistency with other tests (see Blog.find and getBlogs references) and then
assert res.status(500) and res.json({ message: error.message }) as before.
package.json (1)

29-32: 💤 Low value

Consider whether mockingoose is needed for current tests.

mockingoose is added to devDependencies but the test file in this PR uses jest.mock() directly instead of mockingoose's specialized Mongoose mocking utilities. If future tests will use mockingoose's features (like .toReturn() or .reset()), keeping it is fine. Otherwise, it could be deferred until needed.

🤖 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 `@package.json` around lines 29 - 32, The package.json currently adds the
devDependency "mockingoose" but the tests in this PR use jest.mock() directly;
either remove "mockingoose" from devDependencies in package.json and update the
lockfile (to trim unused tooling), or if you intend to use mockingoose's helpers
later, leave it but add a short PR note explaining that future tests will rely
on mockingoose (e.g., for .toReturn()/.reset()) so reviewers know it's
intentional; reference the dependency name "mockingoose" when making the change
or note.
🤖 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 `@agency/server/controllers/__tests__/blogController.test.js`:
- Around line 194-203: The test and controller are inconsistent: change
updateBlog's error handling to mirror deleteBlog by treating database/lookup
rejections (e.g., errors thrown from Blog.findById) as server errors (status
500) while reserving 400 only for validation/save errors; update the updateBlog
controller to catch rejections from Blog.findById and respond with
res.status(500).json({ message: err.message }) (keep validation error handling
for save() as 400) and then adjust the test expectation in
blogController.test.js to expect 500 for the Blog.findById rejection case.
- Around line 133-144: The test currently asserts Blog was called with an object
that includes many explicit undefined fields which couples the test to
implementation details; update the assertion in blogController.test.js to only
assert the important properties (e.g., title, author, category, status) using a
partial matcher like expect.objectContaining({ title: 'New Blog', author: 'John
Doe', category: 'Tech', status: 'published' }) when calling Blog, so it no
longer requires unspecified fields (leave Blog and the test around it intact,
just replace the full literal with an objectContaining matcher).
- Around line 57-65: The test for getBlogs uses a synchronous throw from
Blog.find which doesn't mimic an async rejection; change the mock to reject the
promise (use Blog.find.mockRejectedValue(error) or mockImplementation returning
Promise.reject(error)) so it matches the controller's await/async path and keeps
consistency with other tests (see Blog.find and getBlogs references) and then
assert res.status(500) and res.json({ message: error.message }) as before.

In `@agency/server/package.json`:
- Around line 26-31: The package.json currently includes devDependencies
"mongodb-memory-server" and "supertest" which aren't used by the tests in this
PR; either remove these two packages from the "devDependencies" block to keep
dependencies minimal or, if you plan to add integration tests, add a short
comment in package.json or the test suite referencing their intended use
(mongodb-memory-server for in-memory MongoDB in integration tests and supertest
for HTTP endpoint testing) so future reviewers know they are deliberate; update
the "devDependencies" object (the entries "mongodb-memory-server" and
"supertest") accordingly.

In `@package.json`:
- Around line 29-32: The package.json currently adds the devDependency
"mockingoose" but the tests in this PR use jest.mock() directly; either remove
"mockingoose" from devDependencies in package.json and update the lockfile (to
trim unused tooling), or if you intend to use mockingoose's helpers later, leave
it but add a short PR note explaining that future tests will rely on mockingoose
(e.g., for .toReturn()/.reset()) so reviewers know it's intentional; reference
the dependency name "mockingoose" when making the change or note.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 1b2b7dd1-791d-4b73-acca-f6504972915d

📥 Commits

Reviewing files that changed from the base of the PR and between 6051811 and 352086d.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (5)
  • agency/server/controllers/__tests__/blogController.test.js
  • agency/server/package.json
  • nexus/frontend/src/app/(dashboard)/manufacturing/machines/page.tsx
  • nexus/frontend/src/lib/api.ts
  • package.json

@Adityavanjre Adityavanjre left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

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

Added a Jest unit test suite covering all endpoints (`getBlogs`, `getBlogById`, `createBlog`, `updateBlog`, `deleteBlog`) in `agency/server/controllers/blogController.js`. The test isolates logic by mocking Express requests/responses and the Mongoose Blog model. Also added Jest as a devDependency in agency/server/package.json.

Fixed CI issue by upgrading `ajv` version from `^6.12.6` to `^8.17.1` in the root `package.json` overrides specifically for `@nestjs/cli` to resolve a module not found error when generating Prisma client and building the application, while retaining old `ajv` mapping for ESLint to prevent rule meta mapping errors. Added `mpath` missing dependency in `agency/server`.

Fixed `nexus/frontend` typescript errors in `src/app/(dashboard)/manufacturing/machines/page.tsx` and `src/lib/api.ts` which were causing the build step to fail.

Co-authored-by: Adityavanjre <66417028+Adityavanjre@users.noreply.github.com>
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.

1 participant