Skip to content

Commit 91fccef

Browse files
authored
test(mongodb): verify User schema behaviors under connection state 0 (JhaSourav07#2009)
## Description Fixes JhaSourav07#1416 Added a comprehensive Vitest test case in `models/User.test.ts` to document and verify the schema's behavior when the database connection drops (State 0). **Changes made:** - Utilized Vitest's `vi.spyOn` to mock `mongoose.connection.readyState`, forcing it to return `0` (Disconnected). - Mocked the `User.findOne` database operation to simulate a connection failure by throwing a simulated `ConnectionError`. - Verified that the model fails gracefully and returns the descriptive error rather than crashing the application. - (Optional cleanup) Removed an unused `mockMongoose` variable in `lib/mongodb.test.ts` to clear up an existing ESLint warning. ## Pillar - [ ] 🎨 Pillar 1 — New Theme Design - [ ] 📐 Pillar 2 — Geometric SVG Improvement - [ ] 🕐 Pillar 3 — Timezone Logic Optimization - [x] 🛠️ Other (Bug fix, refactoring, docs) ## Visual Preview *N/A - This PR adds backend database tests; no visual UI changes were made.* ## Checklist before requesting a review: - [x] I have read the `CONTRIBUTING.md` file. - [x] I have tested these changes locally (`localhost:3000/api/streak?user=YOUR_USERNAME`). - [x] I have run `npm run format` and `npm run lint` locally and resolved all errors (CI will fail otherwise). - [x] My commits follow the Conventional Commits format (e.g., `feat(themes): ...`, `fix(calculate): ...`). - [x] I have updated `README.md` if I added a new theme or URL parameter. - [x] I have started the repo. - [x] I have made sure that i have only one commit to merge in this PR. - [x] The SVG output matches the CommitPulse "premium quality" aesthetic standard (no raw elements, smooth animations, correct fonts). - [x] (Recommended) I joined the CommitPulse Discord community for contributor discussions, mentorship, and faster PR support.
2 parents cb3721f + 6f10720 commit 91fccef

4 files changed

Lines changed: 46 additions & 32 deletions

File tree

lib/mongodb.test.ts

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,6 @@ describe('dbConnect', () => {
105105
process.env.MONGODB_URI = 'mongodb://localhost:27017/test';
106106
global.mongoose.conn = null;
107107

108-
const mockMongoose = { connection: 'mock' };
109108
vi.mocked(mongoose.connect).mockRejectedValue(new Error('Database is disconnected'));
110109

111110
await expect(dbConnect()).rejects.toThrow('Database is disconnected');

models/User.test.ts

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -93,4 +93,37 @@ describe('User Model', () => {
9393
readyStateSpy.mockRestore();
9494
});
9595
});
96+
97+
describe('Database Connection State 0 Handling', () => {
98+
it('fails queries gracefully with a ConnectionError when disconnected', async () => {
99+
// Import vi locally to match the pattern used in the State 2 test
100+
const { vi } = await import('vitest');
101+
102+
// 1. Force the mongoose connection state to 0 (Disconnected)
103+
const readyStateSpy = vi
104+
.spyOn(mongoose.connection, 'readyState', 'get')
105+
.mockReturnValue(0 as unknown as typeof mongoose.connection.readyState);
106+
107+
expect(mongoose.connection.readyState).toBe(0);
108+
109+
// 2. Mock a database operation to simulate a connection failure
110+
// Mongoose throws specific errors when bufferCommands is false and state is 0
111+
const mockConnectionError = new Error('Database connection lost');
112+
mockConnectionError.name = 'ConnectionError';
113+
114+
const findOneSpy = vi.spyOn(User, 'findOne').mockRejectedValue(mockConnectionError);
115+
116+
// 3. Verify that attempting to query throws the expected ConnectionError
117+
await expect(User.findOne({ username: 'testuser' })).rejects.toThrow(
118+
'Database connection lost'
119+
);
120+
await expect(User.findOne({ username: 'testuser' })).rejects.toMatchObject({
121+
name: 'ConnectionError',
122+
});
123+
124+
// 4. Clean up mocks to prevent side effects in other tests
125+
readyStateSpy.mockRestore();
126+
findOneSpy.mockRestore();
127+
});
128+
});
96129
});

package-lock.json

Lines changed: 12 additions & 31 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
"gsap": "^3.15.0",
3333
"html-to-image": "^1.11.13",
3434
"lucide-react": "^1.17.0",
35+
"mongodb": "^7.2.0",
3536
"mongoose": "^9.6.2",
3637
"next": "^16.2.3",
3738
"react": "19.2.4",

0 commit comments

Comments
 (0)