aboutsummaryrefslogtreecommitdiff
path: root/src/lib/server/db/groceries.test.ts
blob: b4f50502a6a06557e59f101012795ff2d4b306b6 (plain) (blame)
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
71
72
73

import { describe, it, expect, beforeEach } from 'vitest';
import { drizzle } from 'drizzle-orm/libsql';
import { createClient } from '@libsql/client';
import { groceries } from '$lib/server/db/schema';
import { eq } from 'drizzle-orm';

describe('groceries add', () => {
	const client = createClient({ url: ':memory:' });
	const db = drizzle(client, { schema: { groceries } });

	beforeEach(async () => {
		await db.run(`DROP TABLE IF EXISTS groceries`);
		await db.run(`CREATE TABLE groceries (
			id INTEGER PRIMARY KEY AUTOINCREMENT,
			name TEXT NOT NULL,
			checked INTEGER NOT NULL DEFAULT 0,
			created_at TEXT NOT NULL
		)`);
	});

	async function addItem(name: string) {
		const existing = await db
			.select()
			.from(groceries)
			.where(eq(groceries.name, name))
			.limit(1);

		if (existing.length > 0) {
			await db
				.update(groceries)
				.set({ checked: false })
				.where(eq(groceries.id, existing[0].id));
		} else {
			await db.insert(groceries).values({
				name,
				createdAt: new Date().toISOString(),
			});
		}
	}

	it('creates a new item when name is new', async () => {
		await addItem('milk');

		const items = await db.select().from(groceries);
		expect(items).toHaveLength(1);
		expect(items[0].name).toBe('milk');
		expect(items[0].checked).toBe(false);
	});

	it('unchecks an existing checked item instead of creating duplicate', async () => {
		const now = new Date().toISOString();
		await db
			.insert(groceries)
			.values({ name: 'milk', checked: true, createdAt: now });
		await addItem('milk');

		const items = await db.select().from(groceries);
		expect(items).toHaveLength(1);
		expect(items[0].checked).toBe(false);
	});

	it('keeps an unchecked item unchanged (already on list)', async () => {
		const now = new Date().toISOString();
		await db
			.insert(groceries)
			.values({ name: 'milk', checked: false, createdAt: now });
		await addItem('milk');

		const items = await db.select().from(groceries);
		expect(items).toHaveLength(1);
		expect(items[0].checked).toBe(false);
	});
});