Skip to content

Instantly share code, notes, and snippets.

@thesmart
Created March 7, 2021 22:53
Show Gist options
  • Save thesmart/eda0f945c9ff403606cf722828e25578 to your computer and use it in GitHub Desktop.
Save thesmart/eda0f945c9ff403606cf722828e25578 to your computer and use it in GitHub Desktop.
This is an example showing how Deno's Oak can be tested without network connections
import type {
Server,
ServerRequest,
ServerResponse,
} from "https://deno.land/x/oak@v6.5.0/types.d.ts";
import {
Application,
ListenOptions,
} from "https://deno.land/x/oak@v6.5.0/mod.ts";
class MockServer {
serverClosed = false;
requestStack: ServerRequest[];
constructor(requestStack: ServerRequest[]) {
this.requestStack = requestStack;
}
close(): void {
this.serverClosed = true;
}
async *[Symbol.asyncIterator]() {
for await (const request of this.requestStack) {
yield request;
}
}
}
/**
* Make a mock Oak application that can process requests
* and middleware for testing purposes.
*
* ```js
* const app = new MockApplication();
* app.use(middleware);
* app.makeRequest("/"
* ```
*/
export class MockApplication extends Application {
requestStack: ServerRequest[] = [];
responseStack: ServerResponse[] = [];
constructor() {
super({
serve: (addr: string | ListenOptions): Server => {
return new MockServer(this.requestStack) as Server;
}
});
}
makeRequest(
url = "/",
headersInit: string[][] = [["host", "example.com"]]
) {
this.requestStack.push({
url,
headers: new Headers(headersInit),
respond: (response: ServerResponse) => {
this.responseStack.push(response);
return Promise.resolve();
},
proto: "HTTP/1.1"
} as any);
}
async listen() {
// this port doesn't actually get used
await super.listen(":1337")
while (this.requestStack.pop()) {};
}
}
Deno.test("MockApplication can be used to test middleware.", async function() {
const app = new MockApplication();
let middlewareCalled = 0;
app.use((ctx: Context, next: () => Promise<void>) => {
middlewareCalled += 1;
})
app.makeRequest();
await app.listen();
assertEquals(middlewareCalled, 1);
app.makeRequest();
await app.listen();
assertEquals(middlewareCalled, 2);
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment