chore: update api test suite and include it in run test (#49794)

This commit is contained in:
Oliver Eyton-Williams
2023-03-23 17:57:11 +01:00
committed by GitHub
parent 87d9ade1a7
commit a0f958189e
11 changed files with 124 additions and 63 deletions
+23 -38
View File
@@ -1,5 +1,12 @@
import fastifyAuth0 from 'fastify-auth0-verify';
import Fastify from 'fastify';
import Fastify, {
FastifyBaseLogger,
FastifyHttpOptions,
FastifyInstance,
RawReplyDefaultExpression,
RawRequestDefaultExpression,
RawServerDefault
} from 'fastify';
import middie from '@fastify/middie';
import fastifySession from '@fastify/session';
import fastifyCookie from '@fastify/cookie';
@@ -18,38 +25,26 @@ import {
AUTH0_AUDIENCE,
AUTH0_DOMAIN,
NODE_ENV,
PORT,
MONGOHQ_URL,
SESSION_SECRET
} from './utils/env';
const envToLogger = {
development: {
transport: {
target: 'pino-pretty',
options: {
translateTime: 'HH:MM:ss Z',
ignore: 'pid,hostname'
}
},
level: 'debug'
},
// TODO: is this the right level for production or should we use 'error'?
production: { level: 'fatal' },
test: false
};
export type FastifyInstanceWithTypeProvider = FastifyInstance<
RawServerDefault,
RawRequestDefaultExpression,
RawReplyDefaultExpression,
FastifyBaseLogger,
TypeBoxTypeProvider
>;
const fastify = Fastify({
logger: envToLogger[NODE_ENV]
}).withTypeProvider<TypeBoxTypeProvider>();
export const build = async (
options: FastifyHttpOptions<RawServerDefault, FastifyBaseLogger> = {}
): Promise<FastifyInstanceWithTypeProvider> => {
const fastify = Fastify(options).withTypeProvider<TypeBoxTypeProvider>();
export type FastifyInstanceWithTypeProvider = typeof fastify;
fastify.get('/', async (_request, _reply) => {
return { hello: 'world' };
});
const start = async () => {
fastify.get('/', async (_request, _reply) => {
return { hello: 'world' };
});
// NOTE: Awaited to ensure `.use` is registered on `fastify`
await fastify.register(middie);
await fastify.register(fastifyCookie);
@@ -83,15 +78,5 @@ const start = async () => {
void fastify.register(testRoutes);
void fastify.register(auth0Routes, { prefix: '/auth0' });
void fastify.register(testValidatedRoutes);
try {
const port = Number(PORT);
fastify.log.info(`Starting server on port ${port}`);
await fastify.listen({ port });
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
return fastify;
};
void start();
-18
View File
@@ -1,18 +0,0 @@
import request, { Response } from 'supertest';
import { API_LOCATION as api } from './utils/env';
describe('GET /', () => {
let res: undefined | Response;
beforeAll(async () => {
res = await request(api).get('/');
});
test('have a 200 response', () => {
expect(res?.statusCode).toBe(200);
});
test('return { "hello": "world"}', () => {
expect(res?.body).toEqual({ hello: 'world' });
});
});
+3 -3
View File
@@ -49,9 +49,9 @@
},
"scripts": {
"build": "tsc",
"develop": "nodemon index.ts",
"start": "NODE_ENV=production node index.ts",
"test": "node --test -r ts-node/register **/*.test.ts",
"develop": "nodemon server.ts",
"start": "NODE_ENV=production node server.js",
"test": "jest --force-exit",
"prisma": "MONGOHQ_URL=mongodb://localhost:27017/freecodecamp?directConnection=true prisma",
"postinstall": "prisma generate"
},
+1 -1
View File
@@ -1,6 +1,6 @@
import { Type } from '@sinclair/typebox';
import type { FastifyInstanceWithTypeProvider } from '..';
import type { FastifyInstanceWithTypeProvider } from '../app';
import { responseSchema, subSchema } from '../schemas/example';
export const testValidatedRoutes = (
+28
View File
@@ -0,0 +1,28 @@
import request, { Response } from 'supertest';
import { build } from './app';
describe('GET /', () => {
let res: undefined | Response;
let fastify: undefined | Awaited<ReturnType<typeof build>>;
beforeAll(async () => {
fastify = await build();
await fastify.ready();
}, 20000);
afterAll(async () => {
// Due to a prisma bug, this is not enough, we need to --force-exit jest:
// https://github.com/prisma/prisma/issues/18146
await fastify?.close();
});
test('have a 200 response', async () => {
res = await request(fastify?.server).get('/');
expect(res?.statusCode).toBe(200);
});
test('return { "hello": "world"}', () => {
expect(res?.body).toEqual({ hello: 'world' });
});
});
+33
View File
@@ -0,0 +1,33 @@
import { build } from './app';
import { NODE_ENV, PORT } from './utils/env';
const envToLogger = {
development: {
transport: {
target: 'pino-pretty',
options: {
translateTime: 'HH:MM:ss Z',
ignore: 'pid,hostname'
}
},
level: 'debug'
},
// TODO: is this the right level for production or should we use 'error'?
production: { level: 'fatal' },
test: undefined
};
const start = async () => {
const fastify = await build({ logger: envToLogger[NODE_ENV] });
try {
const port = Number(PORT);
fastify.log.info(`Starting server on port ${port}`);
await fastify.listen({ port });
} catch (err) {
fastify.log.error(err);
process.exit(1);
}
};
void start();
+6 -1
View File
@@ -31,9 +31,14 @@ assert.ok(process.env.AUTH0_AUDIENCE);
assert.ok(process.env.API_LOCATION);
assert.ok(process.env.SESSION_SECRET);
if (process.env.NODE_ENV !== 'development') {
if (process.env.NODE_ENV !== 'development' && process.env.NODE_ENV !== 'test') {
assert.ok(process.env.PORT);
assert.ok(process.env.MONGOHQ_URL);
assert.notEqual(
process.env.SESSION_SECRET,
'a_thirty_two_plus_character_session_secret',
'The session secret should be changed from the default value.'
);
}
export const MONGOHQ_URL =