Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion quotevote-backend/__tests__/unit/authentication.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -158,8 +158,12 @@ describe('Authentication Utils', () => {
const mockUser = {
_id: 'mockId',
username: 'testuser',
name: 'Test User',
email: 'test@example.com',
admin: false,
accountStatus: 'active',
avatar: { topType: 'ShortHairShortFlat', hairColor: 'Brown' },
bio: 'Hello',
comparePassword: jest.fn().mockResolvedValue(true),
};
(User.findOne as jest.Mock).mockResolvedValue(mockUser);
Expand All @@ -170,7 +174,12 @@ describe('Authentication Utils', () => {
expect(jwt.sign).toHaveBeenCalled();
expect(res.json).toHaveBeenCalledWith(expect.objectContaining({
accessToken: 'token',
refreshToken: 'token'
refreshToken: 'token',
user: expect.objectContaining({
username: 'testuser',
avatar: { topType: 'ShortHairShortFlat', hairColor: 'Brown' },
bio: 'Hello',
}),
}));
});
});
Expand Down
161 changes: 161 additions & 0 deletions quotevote-backend/__tests__/unit/resolvers/userResolver.test.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,29 @@
import mongoose from 'mongoose';
import { GraphQLError } from 'graphql';
import { userResolver } from '~/data/resolvers/userResolver';
import User from '~/data/models/User';
import type { GraphQLContext } from '~/types/graphql';

jest.mock('~/data/models/User');

const actorId = '60d5ec49ad414d7a8d5464a0';
const otherId = '60d5ec49ad414d7a8d5464a1';

function mockContext(overrides: Partial<NonNullable<GraphQLContext['user']>> = {}): GraphQLContext {
return {
req: {} as GraphQLContext['req'],
res: {} as GraphQLContext['res'],
pubsub: {} as GraphQLContext['pubsub'],
user: {
_id: actorId,
username: 'alice',
email: 'alice@example.com',
admin: false,
...overrides,
} as NonNullable<GraphQLContext['user']>,
};
}

describe('userResolver', () => {
beforeEach(() => {
jest.clearAllMocks();
Expand Down Expand Up @@ -63,4 +83,145 @@ describe('userResolver', () => {
]);
});
});

describe('Mutation.updateUser', () => {
it('requires authentication', async () => {
await expect(
userResolver.Mutation.updateUser(
null,
{ user: { _id: actorId, bio: 'Hello' } },
{ ...mockContext(), user: null }
)
).rejects.toThrow(GraphQLError);
});

it('updates own bio as plain text', async () => {
(User.findByIdAndUpdate as jest.Mock).mockReturnValue({
lean: jest.fn().mockResolvedValue({
_id: new mongoose.Types.ObjectId(actorId),
username: 'alice',
bio: 'Thoughtful dialogue',
}),
});

const result = await userResolver.Mutation.updateUser(
null,
{ user: { _id: actorId, bio: ' Thoughtful dialogue ' } },
mockContext()
);

expect(User.findByIdAndUpdate).toHaveBeenCalledWith(
actorId,
{ $set: { bio: 'Thoughtful dialogue' } },
{ new: true }
);
expect(result.bio).toBe('Thoughtful dialogue');
});

it('rejects HTML in bio', async () => {
await expect(
userResolver.Mutation.updateUser(
null,
{ user: { _id: actorId, bio: '<b>nope</b>' } },
mockContext()
)
).rejects.toThrow(/plain text/);
expect(User.findByIdAndUpdate).not.toHaveBeenCalled();
});

it('forbids non-admin from updating another user', async () => {
await expect(
userResolver.Mutation.updateUser(
null,
{ user: { _id: otherId, bio: 'Nope' } },
mockContext({ admin: false })
)
).rejects.toThrow(/Not authorized/);
});

it('allows admin to update contributorBadge on another user', async () => {
(User.findByIdAndUpdate as jest.Mock).mockReturnValue({
lean: jest.fn().mockResolvedValue({
_id: new mongoose.Types.ObjectId(otherId),
username: 'bob',
contributorBadge: true,
}),
});

const result = await userResolver.Mutation.updateUser(
null,
{ user: { _id: otherId, contributorBadge: true } },
mockContext({ admin: true })
);

expect(User.findByIdAndUpdate).toHaveBeenCalledWith(
otherId,
{ $set: { contributorBadge: true } },
{ new: true }
);
expect(result.contributorBadge).toBe(true);
});
});

describe('Mutation.updateUserAvatar', () => {
const avatarQualities = {
topType: 'LongHairStraight',
hairColor: 'Brown',
clotheType: 'Hoodie',
};

it('requires authentication', async () => {
await expect(
userResolver.Mutation.updateUserAvatar(
null,
{ user_id: actorId, avatarQualities },
{ ...mockContext(), user: null }
)
).rejects.toThrow(GraphQLError);
});

it('updates own avatar qualities', async () => {
(User.findByIdAndUpdate as jest.Mock).mockReturnValue({
lean: jest.fn().mockResolvedValue({
_id: new mongoose.Types.ObjectId(actorId),
username: 'alice',
avatar: avatarQualities,
}),
});

const result = await userResolver.Mutation.updateUserAvatar(
null,
{ user_id: actorId, avatarQualities },
mockContext()
);

expect(User.findByIdAndUpdate).toHaveBeenCalledWith(
actorId,
{ $set: { avatar: avatarQualities } },
{ new: true }
);
expect(result.avatar).toEqual(avatarQualities);
});

it('forbids updating another user avatar', async () => {
await expect(
userResolver.Mutation.updateUserAvatar(
null,
{ user_id: otherId, avatarQualities },
mockContext({ admin: false })
)
).rejects.toThrow(/Not authorized/);
expect(User.findByIdAndUpdate).not.toHaveBeenCalled();
});

it('rejects non-object avatarQualities', async () => {
await expect(
userResolver.Mutation.updateUserAvatar(
null,
{ user_id: actorId, avatarQualities: null },
mockContext()
)
).rejects.toThrow(/avatarQualities/);
});
});
});
33 changes: 33 additions & 0 deletions quotevote-backend/__tests__/unit/utils/bioValidation.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
import { normalizeBio, BIO_MAX_LENGTH } from '~/data/utils/bioValidation';

describe('bioValidation', () => {
describe('normalizeBio', () => {
it('trims whitespace', () => {
expect(normalizeBio(' hello world ')).toBe('hello world');
});

it('returns empty string for nullish or blank input', () => {
expect(normalizeBio(null)).toBe('');
expect(normalizeBio(undefined)).toBe('');
expect(normalizeBio(' ')).toBe('');
});

it('accepts plain text within the max length', () => {
const bio = 'a'.repeat(BIO_MAX_LENGTH);
expect(normalizeBio(bio)).toBe(bio);
});

it('rejects text longer than the max length', () => {
expect(() => normalizeBio('a'.repeat(BIO_MAX_LENGTH + 1))).toThrow(
`About must be ${BIO_MAX_LENGTH} characters or fewer`
);
});

it('rejects HTML markup', () => {
expect(() => normalizeBio('Hello <script>alert(1)</script>')).toThrow(
'About must be plain text without HTML'
);
expect(() => normalizeBio('<b>bold</b>')).toThrow('About must be plain text without HTML');
});
});
});
30 changes: 30 additions & 0 deletions quotevote-backend/__tests__/unit/utils/serializeDate.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { toIsoDateString } from '~/data/utils/serializeDate';

describe('toIsoDateString', () => {
it('serializes Date instances to ISO strings', () => {
expect(toIsoDateString(new Date('2024-01-15T12:00:00.000Z'))).toBe(
'2024-01-15T12:00:00.000Z'
);
});

it('serializes millisecond epoch numbers to ISO strings', () => {
const ms = Date.UTC(2024, 0, 15);
expect(toIsoDateString(ms)).toBe(new Date(ms).toISOString());
});

it('treats small epoch numbers as seconds', () => {
expect(toIsoDateString(1705276800)).toBe('2024-01-15T00:00:00.000Z');
});

it('serializes numeric timestamp strings', () => {
const ms = Date.UTC(2024, 0, 15);
expect(toIsoDateString(String(ms))).toBe(new Date(ms).toISOString());
});

it('returns empty string for invalid values', () => {
expect(toIsoDateString(null)).toBe('');
expect(toIsoDateString(undefined)).toBe('');
expect(toIsoDateString('not-a-date')).toBe('');
expect(toIsoDateString(new Date('invalid'))).toBe('');
});
});
1 change: 1 addition & 0 deletions quotevote-backend/app/data/inputs/UserInput.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ export const UserInput = new GraphQLInputObjectType({
password: { type: GraphQLString },
quotes: { type: new GraphQLList(GraphQLString) },
avatar: { type: GraphQLString },
bio: { type: GraphQLString },
contributorBadge: { type: GraphQLBoolean },
themePreference: { type: GraphQLString },
},
Expand Down
Loading
Loading