🐛 fix unittests

This commit is contained in:
Flam3rboy 2021-09-20 23:35:37 +02:00
parent cc33e87a14
commit eb2f447d96
4 changed files with 81 additions and 20 deletions

View File

@ -1,3 +1,4 @@
const { Config, initDatabase } = require("@fosscord/util");
const fs = require("fs"); const fs = require("fs");
const path = require("path"); const path = require("path");
const { FosscordServer } = require("../dist/Server"); const { FosscordServer } = require("../dist/Server");
@ -5,8 +6,12 @@ const Server = new FosscordServer({ port: 3001 });
global.server = Server; global.server = Server;
module.exports = async () => { module.exports = async () => {
try { try {
fs.unlinkSync(path.join(__dirname, "..", "database.db")); fs.unlinkSync(path.join(process.cwd(), "database.db"));
} catch {} } catch {}
await initDatabase();
await Config.init();
Config.get().limits.rate.disabled = true;
return await Server.start(); return await Server.start();
}; };

View File

@ -1,2 +1,2 @@
// jest.spyOn(global.console, "log").mockImplementation(() => jest.fn()); jest.spyOn(global.console, "log").mockImplementation(() => jest.fn());
// jest.spyOn(global.console, "info").mockImplementation(() => jest.fn()); jest.spyOn(global.console, "info").mockImplementation(() => jest.fn());

View File

@ -1,4 +1,4 @@
import { DiscordApiErrors, Event, EventData, getPermission, PermissionResolvable, Permissions } from "@fosscord/util"; import { DiscordApiErrors, EVENT, Event, EventData, getPermission, PermissionResolvable, Permissions } from "@fosscord/util";
import { NextFunction, Request, Response } from "express"; import { NextFunction, Request, Response } from "express";
import fs from "fs"; import fs from "fs";
import path from "path"; import path from "path";
@ -38,7 +38,7 @@ export interface RouteOptions {
response?: RouteResponse; response?: RouteResponse;
body?: any; body?: any;
path?: string; path?: string;
event?: EventData | EventData[]; event?: EVENT | EVENT[];
headers?: Record<string, string>; headers?: Record<string, string>;
}; };
} }

View File

@ -2,12 +2,12 @@
// TODO: check every route with different database engine // TODO: check every route with different database engine
import getRouteDescriptions from "../jest/getRouteDescriptions"; import getRouteDescriptions from "../jest/getRouteDescriptions";
import supertest, { Response } from "supertest";
import { join } from "path"; import { join } from "path";
import fs from "fs"; import fs from "fs";
import Ajv from "ajv"; import Ajv from "ajv";
import addFormats from "ajv-formats"; import addFormats from "ajv-formats";
const request = supertest("http://localhost:3001/api"); import fetch from "node-fetch";
import { User } from "@fosscord/util";
const SchemaPath = join(__dirname, "..", "assets", "responses.json"); const SchemaPath = join(__dirname, "..", "assets", "responses.json");
const schemas = JSON.parse(fs.readFileSync(SchemaPath, { encoding: "utf8" })); const schemas = JSON.parse(fs.readFileSync(SchemaPath, { encoding: "utf8" }));
@ -18,34 +18,90 @@ export const ajv = new Ajv({
schemas, schemas,
messages: true, messages: true,
strict: true, strict: true,
strictRequired: true strictRequired: true,
coerceTypes: true
}); });
addFormats(ajv); addFormats(ajv);
var token: string;
var user: User;
beforeAll(async (done) => {
try {
const response = await fetch("http://localhost:3001/api/auth/register", {
method: "POST",
body: JSON.stringify({
fingerprint: "805826570869932034.wR8vi8lGlFBJerErO9LG5NViJFw",
email: "test@example.com",
username: "tester",
password: "wtp9gep9gw",
invite: null,
consent: true,
date_of_birth: "2000-01-01",
gift_code_sku_id: null,
captcha_key: null
}),
headers: {
"content-type": "application/json"
}
});
const json = await response.json();
token = json.token;
user = await (
await fetch(`http://localhost:3001/api/users/@me`, {
headers: { authorization: token }
})
).json();
done();
} catch (error) {
done(error);
}
});
describe("Automatic unit tests with route description middleware", () => { describe("Automatic unit tests with route description middleware", () => {
const routes = getRouteDescriptions(); const routes = getRouteDescriptions();
routes.forEach((route, pathAndMethod) => { routes.forEach((route, pathAndMethod) => {
const [path, method] = pathAndMethod.split("|"); const [path, method] = pathAndMethod.split("|");
test(path, (done) => { test(path, async (done) => {
if (!route.example) { if (!route.test) {
console.log(`${(route as any).file}\nrouter.${method} is missing the test property`); console.log(`${(route as any).file}\nrouter.${method} is missing the test property`);
return done(); return done();
} }
const urlPath = path || route.example?.path; const urlPath = path.replace(":id", user.id) || route.test?.path;
const validate = ajv.getSchema(route.response.body); var validate: any;
if (!validate) return done(new Error(`Response schema ${route.response.body} not found`)); if (route.test.body) {
validate = ajv.getSchema(route.test.body);
if (!validate) return done(new Error(`Response schema ${route.test.body} not found`));
}
request[method](urlPath) var body = "";
.expect(route.response.status)
.expect((err: any, res: Response) => { try {
if (err) return done(err); const response = await fetch(`http://localhost:3001/api${urlPath}`, {
const valid = validate(res.body); method: method.toUpperCase(),
body: JSON.stringify(route.test.body),
headers: { ...route.test.headers, authorization: token }
});
body = await response.text();
expect(response.status, body).toBe(route.test.response.status || 200);
// TODO: check headers
// TODO: expect event
if (validate) {
body = JSON.parse(body);
const valid = validate(body);
if (!valid) return done(validate.errors); if (!valid) return done(validate.errors);
}
} catch (error) {
return done(error);
}
return done(); return done();
}); });
}); });
});
}); });