Setup and teardown APIs
To make testing easier, you can use these APIs to help perform setup and teardown for test cases:
Deno.test.beforeAll
Deno.test.beforeEach
Deno.test.afterAll
Deno.test.afterEach
Here’s a concrete example showing how to set up a test database:
import sqlite from "node:sqlite";
import { assertEquals } from "jsr:@std/assert";
let testDb: sqlite.DatabaseSync;
// Run once before all tests
Deno.test.beforeAll(() => {
testDb = new sqlite.DatabaseSync(":memory:");
testDb.exec(`CREATE TABLE users (
id INTEGER PRIMARY KEY, name TEXT NOT NULL, email TEXT UNIQUE
);
`);
});
// Run before each individual test
Deno.test.beforeEach(() => {
testDb.exec("DELETE FROM users");
const insert = testDb.prepare(
"INSERT INTO users (name, email) VALUES (?, ?)",
);
insert.run("Alice", "alice@example.com");
insert.run("Bob", "bob@example.com");
});
// Run after each individual test
Deno.test.afterEach(() => {
// Clean up test data
testDb.exec("DELETE FROM users");
});
// Run once after all tests
Deno.test.afterAll(() => {
testDb.close();
});
Deno.test("should find user by email", () => {
const query = testDb.prepare("SELECT * FROM users WHERE email = ?");
const user = query.get("alice@example.com");
assertEquals(user?.name, "Alice");
});
Deno.test("should create new user", () => {
const insert = testDb.prepare(
"INSERT INTO users (name, email) VALUES (?, ?)",
);
insert.run("Charlie", "charlie@example.com");
const countQuery = testDb.prepare("SELECT COUNT(*) as count FROM users");
const result = countQuery.get();
assertEquals(result!.count, 3); // 2 from beforeEach + 1 new
});