more db unit tests - best o luck !
All checks were successful
Deploy to Web Server flyer-crawler.projectium.com / deploy (push) Successful in 4m41s

This commit is contained in:
2025-12-06 21:48:27 -08:00
parent 35d3f9d2e7
commit 6f74de3f88
10 changed files with 326 additions and 272 deletions

View File

@@ -25,6 +25,8 @@ import {
getUserFeed,
logSearchQuery,
} from './user.db';
import { resetFailedLoginAttempts } from '../db/user.db';
import { mockPoolInstance } from '../../tests/setup/tests-setup-unit';
import type { Profile } from '../../types';
@@ -73,6 +75,21 @@ describe('User DB Service', () => {
// The implementation returns the profile, not just the user row
expect(result).toEqual(mockProfile);
});
it('should rollback the transaction if creating the user fails', async () => {
// Arrange: Mock the user insert query to fail
mockPoolInstance.query
.mockResolvedValueOnce({ rows: [] }) // BEGIN
.mockResolvedValueOnce({ rows: [] }) // set_config
.mockRejectedValueOnce(new Error('User insert failed')); // INSERT user fails
// Act & Assert
await expect(createUser('fail@example.com', 'badpass', {})).rejects.toThrow('Failed to create user in database.');
expect(mockPoolInstance.connect).toHaveBeenCalled();
expect(mockPoolInstance.query).toHaveBeenCalledWith('BEGIN');
expect(mockPoolInstance.query).toHaveBeenCalledWith('ROLLBACK');
});
});
describe('findUserById', () => {
@@ -205,6 +222,13 @@ describe('User DB Service', () => {
it('should throw an error if a user tries to follow themselves', async () => {
await expect(followUser('user-1', 'user-1')).rejects.toThrow('A user cannot follow themselves.');
});
it('should throw ForeignKeyConstraintError if a user does not exist', async () => {
const dbError = new Error('violates foreign key constraint');
(dbError as any).code = '23503';
mockPoolInstance.query.mockRejectedValue(dbError);
await expect(followUser('user-1', 'non-existent-user')).rejects.toThrow('One or both of the specified users do not exist.');
});
});
describe('unfollowUser', () => {
@@ -231,4 +255,12 @@ describe('User DB Service', () => {
expect(mockPoolInstance.query).toHaveBeenCalledWith(expect.stringContaining('INSERT INTO public.search_queries'), [queryData.userId, queryData.queryText, queryData.resultCount, queryData.wasSuccessful]);
});
});
describe('resetFailedLoginAttempts', () => {
it('should execute an UPDATE query to reset failed attempts and set last_login_ip', async () => {
mockPoolInstance.query.mockResolvedValue({ rows: [] });
await resetFailedLoginAttempts('user-123', '192.168.1.1');
expect(mockPoolInstance.query).toHaveBeenCalledWith(expect.stringContaining('UPDATE public.users SET failed_login_attempts = 0'), ['user-123', '192.168.1.1']);
});
});
});