summary refs log tree commit diff
path: root/api/tests/routes.test.ts
blob: e913e0dcb60a971d48379f0f45ddf1fede1ae8b3 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// TODO: check every route based on route() parameters: https://github.com/fosscord/fosscord-server/issues/308
// TODO: check every route with different database engine

import getRouteDescriptions from "../jest/getRouteDescriptions";
import supertest, { Response } from "supertest";
import path from "path";
import fs from "fs";
import Ajv from "ajv";
import addFormats from "ajv-formats";
const request = supertest("http://localhost:3001/api");

const SchemaPath = path.join(__dirname, "..", "assets", "responses.json");
const schemas = JSON.parse(fs.readFileSync(SchemaPath, { encoding: "utf8" }));
export const ajv = new Ajv({
	allErrors: true,
	parseDate: true,
	allowDate: true,
	schemas,
	messages: true,
	strict: true,
	strictRequired: true
});
addFormats(ajv);

describe("Automatic unit tests with route description middleware", () => {
	const routes = getRouteDescriptions();

	routes.forEach((route, pathAndMethod) => {
		const [path, method] = pathAndMethod.split("|");
		test(path, (done) => {
			if (!route.example) {
				console.log(`Route ${path} is missing the example property`);
				return done();
			}
			if (!route.response) {
				console.log(`Route ${path} is missing the response property`);
				return done();
			}
			const urlPath = path || route.example?.path;
			const validate = ajv.getSchema(route.response.body);
			if (!validate) return done(new Error(`Response schema ${route.response.body} not found`));

			request[method](urlPath)
				.expect(route.response.status)
				.expect((err: any, res: Response) => {
					if (err) return done(err);
					const valid = validate(res.body);
					if (!valid) return done(validate.errors);

					return done();
				});
		});
	});
});