aboutsummaryrefslogtreecommitdiff
path: root/src/lib/server/db/groceries.test.ts
blob: 143e4da44235d248b8e247eb5a3ad4b7fc059009 (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

import { describe, it, expect, beforeEach } from 'vitest';
import { groceries, categories } from '$lib/server/db/schema';
import { eq } from 'drizzle-orm';
import { createTestDb, type TestDb } from './test-helper';

describe('groceries add', () => {
	let db: TestDb['db'];

	beforeEach(async () => {
		db = (await createTestDb()).db;
	});

	async function addItem(name: string, categoryId?: number | null) {
		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,
					categoryId: categoryId ?? existing[0].categoryId,
				})
				.where(eq(groceries.id, existing[0].id));
		} else {
			await db.insert(groceries).values({
				name,
				categoryId,
				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);
	});
});