Last active
June 19, 2023 16:52
-
-
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 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
// 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