Skip to content

Instantly share code, notes, and snippets.

@disintegrator
Last active June 19, 2023 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save disintegrator/35b6a6a87dbad54fada430d8f8efa905 to your computer and use it in GitHub Desktop.
Save disintegrator/35b6a6a87dbad54fada430d8f8efa905 to your computer and use it in GitHub Desktop.
A sample test helper used to acquire resources and automatically tear them down with the upcoming `using` keyword.
// This is untested code. More of a proof of concept for what's to come...
async function $acquire<
Resource
>(fn: () => Promise<readonly [resource: Resource, teadown?: () => void]>) {
let [resource, teardown = () => {}] = await fn();
return {
resource,
[Symbol.dispose]: teardown,
}
}
type Database = {
query(sql: string, ...placeholders: string[]): any[],
close(): void,
};
async function getTestDatabase(): Promise<Database> {
return {
query() { return [] },
close() {},
}
}
// Framework-agnostic self-contained tests where resources like databases
// can be setup and destroyed seemlessly. No more beforeEach / afterEach!
it("works like a charm", async () => {
using {resource: db} = await $acquire(async () => { // ❤️❤️❤️
let db = await getTestDatabase()
return [db, () => db.close()]
})
let result = db.query("select * from products where id = '?'", "123")
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment