Skip to content

Commit

Permalink
add tests
Browse files Browse the repository at this point in the history
  • Loading branch information
jgunnCO committed Apr 24, 2024
1 parent 3d4f0e5 commit b1b4907
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 1 deletion.
1 change: 0 additions & 1 deletion packages/applicant/src/pages/api/csrf.page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import { logger } from '../../utils/logger';

const CSRF_SECRET_ARN = process.env.CSRF_SECRET_ARN;
const hostDomain = 'localhost:3000';

const client = new SecretsManagerClient();

const fetchSecret = async () => {
Expand Down
74 changes: 74 additions & 0 deletions packages/applicant/src/pages/api/csrf.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
import { NextApiRequest, NextApiResponse } from 'next';
import csrfHandler from './csrf.page';

const mockCsrfSecret = 'csrfSecret';

function mockSecretsManagerClient() {
return {
send() {
return { SecretString: JSON.stringify({ csrfSecret: mockCsrfSecret }) };
},
};
}

jest.mock('@aws-sdk/client-secrets-manager', () => {
return {
...jest.requireActual('@aws-sdk/client-secrets-manager'),
SecretsManagerClient: mockSecretsManagerClient,
};
});

jest.mock('../../utils/constants', () => ({
IS_PRODUCTION: true,
}));

const getResponse = (overrides = {}) =>
({
redirect: jest.fn(),
status: jest.fn(function () {
return this;
}),
json: jest.fn(function () {
return this;
}),
...overrides,
} as unknown as NextApiResponse);

describe('/api/csrf', () => {
it('responds with 200 and expected payload to request from expected local address', async () => {
const req = {
headers: { host: 'localhost:3000', 'x-forwarded-for': '::1' },
} as unknown as NextApiRequest;

const res = getResponse();

await csrfHandler(req, res);

expect(res.status).toHaveBeenCalledWith(200);
expect(res.json).toHaveBeenCalledWith({ secret: mockCsrfSecret });
});

it('responds 404 when host header not localhost:3000', async () => {
const req = {
headers: { host: 'https://www.google.com', 'x-forwarded-for': '::1' },
} as unknown as NextApiRequest;

const res = getResponse();

await csrfHandler(req, res);

expect(res.status).toHaveBeenCalledWith(404);
});

it('responds 404 when x-forwarded-for header not ::1', async () => {
const req = {
headers: { host: 'localhost:3000', 'x-forwarded-for': '1.2.3.4' },
} as unknown as NextApiRequest;

const res = getResponse();

await csrfHandler(req, res);

expect(res.status).toHaveBeenCalledWith(404);
});
});

0 comments on commit b1b4907

Please sign in to comment.