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
151 changes: 151 additions & 0 deletions netlify/functions-src/functions/modules/users/toggleAvatar.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,151 @@
import { toggleAvatarHandler, ToggleAvatarRequest } from './toggleAvatar';
import { getCollection } from '../../utils/db';
import { ObjectId } from 'mongodb';
import { AuthContext, HandlerEventWithBody, AuthUser } from '../../types';
import { HandlerContext, HandlerEvent } from '@netlify/functions';

jest.mock('../../utils/db');

interface ExtendedAuthUser extends AuthUser {
email_verified?: boolean;
picture?: string;
}

describe('toggleAvatarHandler', () => {
const collectionMock = {
findOne: jest.fn(),
findOneAndUpdate: jest.fn(),
};

const baseEvent: HandlerEvent = {
body: null,
headers: {},
multiValueHeaders: {},
httpMethod: 'POST',
isBase64Encoded: false,
path: '',
queryStringParameters: null,
multiValueQueryStringParameters: null,
rawQuery: '',
rawUrl: '',
};

const baseContext: HandlerContext = {
callbackWaitsForEmptyEventLoop: true,
functionName: 'toggleAvatar',
functionVersion: '1',
invokedFunctionArn: '',
memoryLimitInMB: '128',
awsRequestId: '',
logGroupName: '',
logStreamName: '',
getRemainingTimeInMillis: () => 0,
done: () => {},
fail: () => {},
succeed: () => {},
};

beforeEach(() => {
jest.clearAllMocks();
// In Jest 26, fulfilling a complex interface like Collection without casting is impossible.
// We use a single centralized cast here to satisfy the requirement as much as possible.
const mocked = getCollection as unknown as jest.Mock;
mocked.mockReturnValue(collectionMock);
});

it('should return email_verified in the response', async () => {
const mockId = new ObjectId();
const mockUser = {
_id: mockId,
email: '[email protected]',
auth0Id: 'google-oauth2|123',
};

collectionMock.findOne.mockResolvedValue(mockUser);
collectionMock.findOneAndUpdate.mockResolvedValue(mockUser);

const event: HandlerEventWithBody<ToggleAvatarRequest> = {
...baseEvent,
parsedBody: { useGravatar: true },
};

const context: AuthContext<ExtendedAuthUser> = {
...baseContext,
user: {
auth0Id: 'google-oauth2|123',
email_verified: true,
picture: 'https://google.com/pic.jpg',
},
};

const response = await toggleAvatarHandler(event, context);
const body = JSON.parse(response.body || '{}');

expect(response.statusCode).toBe(200);
expect(body.success).toBe(true);
expect(body.data).toMatchObject({
email_verified: true,
});
});

it('should return false for email_verified if it is false in context', async () => {
const mockId = new ObjectId();
const mockUser = {
_id: mockId,
email: '[email protected]',
auth0Id: 'google-oauth2|123',
};

collectionMock.findOne.mockResolvedValue(mockUser);
collectionMock.findOneAndUpdate.mockResolvedValue(mockUser);

const event: HandlerEventWithBody<ToggleAvatarRequest> = {
...baseEvent,
parsedBody: { useGravatar: true },
};

const context: AuthContext<ExtendedAuthUser> = {
...baseContext,
user: {
auth0Id: 'google-oauth2|123',
email_verified: false,
picture: 'https://google.com/pic.jpg',
},
};

const response = await toggleAvatarHandler(event, context);
const body = JSON.parse(response.body || '{}');

expect(body.data.email_verified).toBe(false);
});

it('should return undefined for email_verified if it is missing in context', async () => {
const mockId = new ObjectId();
const mockUser = {
_id: mockId,
email: '[email protected]',
auth0Id: 'google-oauth2|123',
};

collectionMock.findOne.mockResolvedValue(mockUser);
collectionMock.findOneAndUpdate.mockResolvedValue(mockUser);

const event: HandlerEventWithBody<ToggleAvatarRequest> = {
...baseEvent,
parsedBody: { useGravatar: true },
};

const context: AuthContext<ExtendedAuthUser> = {
...baseContext,
user: {
auth0Id: 'google-oauth2|123',
picture: 'https://google.com/pic.jpg',
},
};

const response = await toggleAvatarHandler(event, context);
const body = JSON.parse(response.body || '{}');

expect(body.data.email_verified).toBeUndefined();
});
});
11 changes: 7 additions & 4 deletions netlify/functions-src/functions/modules/users/toggleAvatar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@ import { getUserBy, upsertUser } from '../../data/users';
import { UserDto } from '../../common/dto/user.dto';
import crypto from 'crypto';

export type ToggleAvatarRequest = {
useGravatar: boolean;
};

function getGravatarUrl(email: string): string {
const hash = crypto
.createHash('md5')
Expand All @@ -12,9 +16,6 @@ function getGravatarUrl(email: string): string {
return `https://www.gravatar.com/avatar/${hash}?s=200&d=identicon`;
}

type ToggleAvatarRequest = {
useGravatar: boolean;
};

export const toggleAvatarHandler: ApiHandler<ToggleAvatarRequest> = async (event, context) => {
try {
Expand Down Expand Up @@ -55,11 +56,13 @@ export const toggleAvatarHandler: ApiHandler<ToggleAvatarRequest> = async (event
return success({
data: {
...updatedUser,
email_verified: context.user?.email_verified,
auth0Picture: context.user?.picture,
auth0Id: updatedUser.auth0Id,
},
});
} catch (e) {
return error((e as Error).message, 500);
const message = e instanceof Error ? e.message : String(e);
return error(message, 500);
}
};
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,9 @@
"build": "next build",
"start": "next dev",
"lint": "next lint",
"test": "yarn test:unit && yarn test:e2e:run",
"test": "yarn test:unit && yarn test:functions && yarn test:e2e:run",
"test:unit": "react-scripts test",
"test:functions": "jest --env=node netlify/functions-src/functions",
"test:unit:update-snapshot": "react-scripts test -u",
"golden": "yarn prettier",
"predeploy": "yarn run build",
Expand Down