1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
import { users } from "@hoarder/db/schema";
import { getInMemoryDB } from "@hoarder/db/drizzle";
import { appRouter } from "./routers/_app";
import { createCallerFactory } from "./index";
export function getTestDB() {
return getInMemoryDB(true);
}
export type TestDB = ReturnType<typeof getTestDB>;
export async function seedUsers(db: TestDB) {
return await db
.insert(users)
.values([
{
name: "Test User 1",
email: "test1@test.com",
},
{
name: "Test User 2",
email: "test2@test.com",
},
])
.returning();
}
export function getApiCaller(db: TestDB, userId?: string) {
const createCaller = createCallerFactory(appRouter);
return createCaller({
user: userId
? {
id: userId,
role: "user",
}
: null,
db,
});
}
export type APICallerType = ReturnType<typeof getApiCaller>;
export interface CustomTestContext {
apiCallers: APICallerType[];
unauthedAPICaller: APICallerType;
db: TestDB;
}
export async function buildTestContext(
seedDB: boolean,
): Promise<CustomTestContext> {
const db = getTestDB();
let users: Awaited<ReturnType<typeof seedUsers>> = [];
if (seedDB) {
users = await seedUsers(db);
}
const callers = users.map((u) => getApiCaller(db, u.id));
return {
apiCallers: callers,
unauthedAPICaller: getApiCaller(db),
db,
};
}
export function defaultBeforeEach(seedDB: boolean = true) {
return async (context: object) => {
Object.assign(context, await buildTestContext(seedDB));
};
}
|