📄 src/models/test/level-state.test.ts
D-OPEN SOVEREIGN
Documentation & Insights
@vitest-environment jsdom1/*
2 * Copyright (c) 2026 DataPond D-Library Pty Ltd. ("The Sanctuary")
3 * Non-Profit Public Library — The World Library
4 *
5 * D-SAFE Certification issued by POND Enterprise.
6 * Published under the D-Open Code Sovereign Licence v1.0 framework
7 * DataPond D-Library All exclusive Right reserved on modifiying the code - CC Attribution to data pond, Non modifiable, Non Commercial.
8 * https://registry.world.bibliotech.com/licence
9 * Source code donated to DataPond D-Library by it's author: data pond.
10 *
11 * Technical Guardian ("The Shield"): Pond Enterprise Pty Ltd. (ACN 694 747 987)
12 * All liability claims about D-SAFE certification issues coming from the published D-Safe direction must be addressed with Pond Enterprise Pty Ltd.
13 * Code Modification automatically voids the certified liability protection provided by Pond Enterprise.
14 */
15/**
16 * @vitest-environment jsdom
17 */
18import { describe, it, expect, vi } from 'vitest';
19import { getLevel, subscribeLevel } from '../level-state.ts';
20
21describe('level-state', () => {
22 it('getLevel returns default 1, 0 if unknown', () => {
23 const state = getLevel('unknown_user');
24 expect(state).toEqual({ level: 1, progress: 0 });
25 });
26
27 it('processes LevelUpdate event and updates correctly', () => {
28 // Setup listener
29 const listener = vi.fn();
30 const unsubscribe = subscribeLevel(listener);
31
32 // Dispatch a CustomEvent matching the DOM LevelUpdate
33 const event = new CustomEvent('LevelUpdate', {
34 detail: { username: 'test_user', level: 2.25 }
35 });
36 window.dispatchEvent(event);
37
38 // Verify state is stored
39 const state = getLevel('test_user');
40 expect(state.level).toBe(3); // Math.floor(2.25) + 1 = 3
41 expect(state.progress).toBe(25); // 100 * 0.25 = 25
42
43 // Verify listener was called
44 expect(listener).toHaveBeenCalledWith('test_user');
45
46 // Cleanup
47 unsubscribe();
48
49 // Dispatch again, listener shouldn't be called
50 window.dispatchEvent(new CustomEvent('LevelUpdate', {
51 detail: { username: 'test_user', level: 3.5 }
52 }));
53
54 expect(listener).toHaveBeenCalledTimes(1); // not called again
55
56 const newState = getLevel('test_user');
57 expect(newState.level).toBe(4);
58 expect(newState.progress).toBe(50);
59 });
60
61 it('ignores LevelUpdate if username is missing', () => {
62 const event = new CustomEvent('LevelUpdate', {
63 detail: { level: 5.0 }
64 });
65
66 const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
67 window.dispatchEvent(event);
68
69 expect(consoleSpy).toHaveBeenCalled();
70 consoleSpy.mockRestore();
71 });
72});
73