summary refs log tree commit diff
path: root/api/tests
diff options
context:
space:
mode:
authorFlam3rboy <34555296+Flam3rboy@users.noreply.github.com>2021-09-18 01:50:29 +0200
committerFlam3rboy <34555296+Flam3rboy@users.noreply.github.com>2021-09-18 01:50:29 +0200
commita7bf2955910772409ea9c3c6c32c0394c76f34b8 (patch)
tree3a59c1b7817039aebbde76f45327a8a71fa60600 /api/tests
parent:art: use typescript plugin that converts to relative paths (diff)
downloadserver-a7bf2955910772409ea9c3c6c32c0394c76f34b8.tar.xz
:sparkles: jest automatic tests
Diffstat (limited to 'api/tests')
-rw-r--r--api/tests/automatic.test.js2
-rw-r--r--api/tests/routes.test.ts54
2 files changed, 54 insertions, 2 deletions
diff --git a/api/tests/automatic.test.js b/api/tests/automatic.test.js
deleted file mode 100644
index 2d0a9fcb..00000000
--- a/api/tests/automatic.test.js
+++ /dev/null
@@ -1,2 +0,0 @@
-// TODO: check every route based on route() paramters: https://github.com/fosscord/fosscord-server/issues/308
-// TODO: check every route with different database engine
diff --git a/api/tests/routes.test.ts b/api/tests/routes.test.ts
new file mode 100644
index 00000000..e913e0dc
--- /dev/null
+++ b/api/tests/routes.test.ts
@@ -0,0 +1,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();
+				});
+		});
+	});
+});