This repository has been archived by the owner on May 22, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Testing
Marcel Kloubert edited this page Mar 14, 2023
·
1 revision
About [↑]
The two decorators @Describe() and @It() are useful tools to save metadata into Controllers. This can be used in contextes, like unit testing.
While @Describe()
can be used to group tests, does @It()
setup one or more test scenarios for specific request methods:
import {
Controller,
ControllerBase,
Describe,
GET,
IHttpRequest,
IHttpResponse,
It,
} from "@egomobile/http-server";
@Controller()
@Describe("My controller")
export default class MyController extends ControllerBase {
@GET("/foo/:bar")
@It("should return BUZZ in code with status 202", {
expectations: {
body: "BUZZ",
status: 202,
},
parameters: {
bar: "buzz",
},
})
async index(request: IHttpRequest, response: IHttpResponse) {
response.writeHead(202);
response.write(request.params!.bar.toUpperCase());
}
}
Both decorators only collect the data. This library does not implement a working testing framework by itself!
What it does, is to provide an event pattern. An application can listen to an event, called test
:
import { createServer } from "@egomobile/http-server";
const app = createServer();
// event, that is executed, if a test,
// setupped by `@It()`, is requested
app.once("test", async (context) => {
// context => https://egomobile.github.io/node-http-server/interfaces/ITestEventHandlerContext.html
});
await app.test();
// alternative:
//
// if you set `EGO_RUN_SETUP` to a truthy value like `1`
// the server does not start listening, instead it simply
// runs `app.test()`
//
// await app.listen();
In many HTTP server application, the SuperTest library is used to realize endpoint testing.
It is quite simple to integrate its features into the test framework:
import assert from "assert";
import supertest from "supertest";
import { createServer } from "@egomobile/http-server";
/// ...
// event, that is executed, if a test is requested
app.once("test", async (context) => {
const {
body,
description,
escapedRoute,
expectations,
group,
headers,
httpMethod,
server,
} = context;
try {
process.stdout.write(`Running test [${group}] '${description}' ... `);
// prepare request ...
// HTTP method ...
let request = supertest(server)[httpMethod](escapedRoute);
// request headers ...
for (const [headerName, headerValue] of Object.entries(headers)) {
request = request.set(headerName, headerValue);
}
// send it
const response = await request.send(body);
assert.strictEqual(response.statusCode, expectations.status);
// maybe some more code checking headers and
// body data from `expectations` ...
process.stdout.write(`✅\n`);
} catch (error) {
process.stdout.write(`❌: ${error}\n`);
}
});
/// ...
licensed under GDFL 1.3 - © Next.e.GO Mobile SE