Testing
Introduction
Testing your application provides peace of mind that you can make changes, add new features and know that you are not breaking existing functionality. Raptor takes testing seriously - there are over 100 individual test scenarios across the framework and first-party packages. The design and architecture of Raptor makes testing a breeze and this guide aims to demonstrate how to test your own Raptor applications.
Getting Started
The following tests have been written with the built-in Deno test functions. You are free to use whichever test library is your preference, the examples below should translate.
Context (Request)
The Context object is one of Raptor's core building blocks, and testing it is surprisingly simple. The first thing we need to do is mock the Request which is passed to the Kernel's Context object.
type MockRequestOptions = {
url?: string;
method?: string;
headers?: Record<string, string>;
}
const mockRequest = (options: MockRequestOptions = {}): Request => {
return new Request(options.url ?? "http://localhost/", {
method: options.method ?? "GET",
headers: options.headers,
});
}Once you have a mock function defined, you can then reuse that across your test suite.
/// <reference lib="deno.ns" />
import { Kernel } from "@raptor/kernel";
import { assertEquals } from "jsr:@std/assert";
import mockRequest from "./mock-request.ts";
Deno.test("test middleware responds with correct body", () => {
const app = new Kernel();
app.add(() => "Hello, Dr Malcolm!");
const response = await app.respond(mockRequest());
const body = await response.text();
assertEquals(body, "Hello, Dr Malcolm!");
});If you are using the first-party Router package, you can use this same pattern to test routes.
/// <reference lib="deno.ns" />
import { assertEquals } from "jsr:@std/assert";
import { Route, Router } from "@raptor/router";
import { Kernel, HttpMethod } from "@raptor/kernel";
import routes from "./routes.ts";
import mockRequest from "./mock-request.ts";
Deno.test("test route responds with correct body", () => {
const app = new Kernel();
const router = new Router();
// Your application code lives in "routes".
// Within these routes contains a "/test" route.
router.add(routes);
app.add((context: Context) => router.handle(context));
const response = await app.respond(mockRequest("http://localhost/test"));
const body = await response.text();
assertEquals(body, "Test route");
});