Created
March 7, 2021 22:53
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { | |
Server, | |
ServerRequest, | |
ServerResponse, | |
} from "https://deno.land/x/[email protected]/types.d.ts"; | |
import { | |
Application, | |
ListenOptions, | |
} from "https://deno.land/x/[email protected]/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