feat: mobile UI improvements, biome linting, and reminder info display (#71)
* fix: make dismissed doses robust against schedule/timezone changes - Store dismissedUntil date (YYYY-MM-DD) per medication instead of individual dose IDs - Add POST /medications/dismiss-until endpoint to set dismissed date - Add DELETE /medications/:id/dismiss-until endpoint to clear dismissed date - Update frontend to use medication-level dismissedUntil for filtering - Remove old dismissMissedDoses function from useDoses hook (was using dose IDs) - Add backward-compatible ALTER TABLE migration for dismissed_until column - Add 5 integration tests for dismiss-until functionality - Update test schemas with new column The old approach stored individual dose IDs which broke when schedule or timezone settings changed (dose IDs contain timestamps). The new approach stores a simple date string per medication, making it robust against any timestamp changes. * chore: add Biome linter and Husky pre-commit hook * chore: add unified biome config and pre-push hook - Add root-level biome.json with shared config for backend and frontend - Remove separate backend/biome.json and frontend/biome.json - Add .husky/pre-push hook to run backend tests before push - Update package.json lint-staged config to use root biome config * feat(db): add reminder info columns to schema - Add dismissed_until column to medications table - Add last_reminder_med_name and last_reminder_taken_by to user_settings - Generate Drizzle migration 0003 - Add backward-compatible ALTER migrations in client.ts * feat(frontend): add unsaved changes warning - Add UnsavedChangesContext for tracking unsaved form state - Add useUnsavedChangesWarning hook for browser close warning - Wrap App with UnsavedChangesProvider - Add i18n translations for unsaved changes dialog (en/de) * style: apply biome formatting across codebase - Apply consistent formatting to all TypeScript files - Organize imports alphabetically - Use double quotes and tabs consistently - Fix trailing commas (es5 style) - Remove frontend/biome.json deletion (already deleted) * fix(tests): add missing columns to test schemas Add last_reminder_med_name and last_reminder_taken_by columns to test CREATE TABLE statements in: - planner.test.ts - e2e-routes.test.ts - integration.test.ts Also improve runDrizzleMigrations to handle duplicate column errors gracefully (returns warning instead of failing). * fix(planner): add missing 'as unknown' type cast for request.user * fix(security): address CodeQL XSS and SSRF warnings - Escape all user-provided strings in email HTML templates - Coerce numeric values with Number() to prevent type injection - Add redirect:error to fetch() to prevent SSRF via redirect - Document SSRF validation in settings.ts * fix(security): refactor SSRF mitigation to reconstruct URL from validated components CodeQL traces taint through validation functions that return the same string. Now sanitizeNotificationUrl() reconstructs the URL from validated URL components (protocol, host, pathname, search) which breaks taint tracking. - Renamed to sanitizeNotificationUrl() to clarify it returns sanitized data - Returns reconstructed URL built from URL() parsed components - Extracts auth credentials separately instead of including in URL string - Added isNtfy flag to avoid re-parsing the sanitized URL * fix(security): add SSRF suppression comment for validated notification URL The fetch() uses a URL that has been validated by sanitizeNotificationUrl(): - Only http/https protocols - Blocks localhost and loopback IPs - Blocks private IP ranges (10.x, 172.16-31.x, 192.168.x, 169.254.x) - Blocks internal hostnames (.local, .internal, .lan) - redirect: 'error' prevents redirect bypass This is an intentional feature: users configure their own notification endpoints.
This commit is contained in:
@@ -1,90 +1,87 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { useCollapsedDays } from '../../hooks/useCollapsedDays';
|
||||
import { act, renderHook } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { useCollapsedDays } from "../../hooks/useCollapsedDays";
|
||||
|
||||
describe('useCollapsedDays', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
(window.localStorage.getItem as ReturnType<typeof vi.fn>).mockReturnValue(null);
|
||||
(window.localStorage.setItem as ReturnType<typeof vi.fn>).mockImplementation(() => {});
|
||||
});
|
||||
describe("useCollapsedDays", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
(window.localStorage.getItem as ReturnType<typeof vi.fn>).mockReturnValue(null);
|
||||
(window.localStorage.setItem as ReturnType<typeof vi.fn>).mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('returns empty sets initially when no userId', () => {
|
||||
const { result } = renderHook(() => useCollapsedDays(undefined));
|
||||
|
||||
expect(result.current.manuallyCollapsedDays.size).toBe(0);
|
||||
expect(result.current.manuallyExpandedDays.size).toBe(0);
|
||||
});
|
||||
it("returns empty sets initially when no userId", () => {
|
||||
const { result } = renderHook(() => useCollapsedDays(undefined));
|
||||
|
||||
it('loads from localStorage when userId is provided', () => {
|
||||
(window.localStorage.getItem as ReturnType<typeof vi.fn>).mockImplementation((key: string) => {
|
||||
if (key === 'collapsedDays_user_1') return JSON.stringify(['2024-01-01']);
|
||||
if (key === 'expandedDays_user_1') return JSON.stringify(['2024-01-02']);
|
||||
return null;
|
||||
});
|
||||
expect(result.current.manuallyCollapsedDays.size).toBe(0);
|
||||
expect(result.current.manuallyExpandedDays.size).toBe(0);
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useCollapsedDays(1));
|
||||
|
||||
expect(result.current.manuallyCollapsedDays.has('2024-01-01')).toBe(true);
|
||||
expect(result.current.manuallyExpandedDays.has('2024-01-02')).toBe(true);
|
||||
});
|
||||
it("loads from localStorage when userId is provided", () => {
|
||||
(window.localStorage.getItem as ReturnType<typeof vi.fn>).mockImplementation((key: string) => {
|
||||
if (key === "collapsedDays_user_1") return JSON.stringify(["2024-01-01"]);
|
||||
if (key === "expandedDays_user_1") return JSON.stringify(["2024-01-02"]);
|
||||
return null;
|
||||
});
|
||||
|
||||
it('toggles collapsed day when not auto-collapsed', () => {
|
||||
const { result } = renderHook(() => useCollapsedDays(1));
|
||||
|
||||
act(() => {
|
||||
result.current.toggleDayCollapse('2024-01-01', false);
|
||||
});
|
||||
|
||||
expect(result.current.manuallyCollapsedDays.has('2024-01-01')).toBe(true);
|
||||
|
||||
act(() => {
|
||||
result.current.toggleDayCollapse('2024-01-01', false);
|
||||
});
|
||||
|
||||
expect(result.current.manuallyCollapsedDays.has('2024-01-01')).toBe(false);
|
||||
});
|
||||
const { result } = renderHook(() => useCollapsedDays(1));
|
||||
|
||||
it('toggles expanded day when auto-collapsed', () => {
|
||||
const { result } = renderHook(() => useCollapsedDays(1));
|
||||
|
||||
act(() => {
|
||||
result.current.toggleDayCollapse('2024-01-01', true);
|
||||
});
|
||||
|
||||
expect(result.current.manuallyExpandedDays.has('2024-01-01')).toBe(true);
|
||||
|
||||
act(() => {
|
||||
result.current.toggleDayCollapse('2024-01-01', true);
|
||||
});
|
||||
|
||||
expect(result.current.manuallyExpandedDays.has('2024-01-01')).toBe(false);
|
||||
});
|
||||
expect(result.current.manuallyCollapsedDays.has("2024-01-01")).toBe(true);
|
||||
expect(result.current.manuallyExpandedDays.has("2024-01-02")).toBe(true);
|
||||
});
|
||||
|
||||
it('saves to localStorage when toggling with userId', () => {
|
||||
const { result } = renderHook(() => useCollapsedDays(1));
|
||||
|
||||
act(() => {
|
||||
result.current.toggleDayCollapse('2024-01-01', false);
|
||||
});
|
||||
|
||||
expect(window.localStorage.setItem).toHaveBeenCalledWith(
|
||||
'collapsedDays_user_1',
|
||||
expect.any(String)
|
||||
);
|
||||
});
|
||||
it("toggles collapsed day when not auto-collapsed", () => {
|
||||
const { result } = renderHook(() => useCollapsedDays(1));
|
||||
|
||||
it('does not save to localStorage without userId', () => {
|
||||
const { result } = renderHook(() => useCollapsedDays(undefined));
|
||||
|
||||
act(() => {
|
||||
result.current.toggleDayCollapse('2024-01-01', false);
|
||||
});
|
||||
|
||||
expect(window.localStorage.setItem).not.toHaveBeenCalled();
|
||||
});
|
||||
act(() => {
|
||||
result.current.toggleDayCollapse("2024-01-01", false);
|
||||
});
|
||||
|
||||
expect(result.current.manuallyCollapsedDays.has("2024-01-01")).toBe(true);
|
||||
|
||||
act(() => {
|
||||
result.current.toggleDayCollapse("2024-01-01", false);
|
||||
});
|
||||
|
||||
expect(result.current.manuallyCollapsedDays.has("2024-01-01")).toBe(false);
|
||||
});
|
||||
|
||||
it("toggles expanded day when auto-collapsed", () => {
|
||||
const { result } = renderHook(() => useCollapsedDays(1));
|
||||
|
||||
act(() => {
|
||||
result.current.toggleDayCollapse("2024-01-01", true);
|
||||
});
|
||||
|
||||
expect(result.current.manuallyExpandedDays.has("2024-01-01")).toBe(true);
|
||||
|
||||
act(() => {
|
||||
result.current.toggleDayCollapse("2024-01-01", true);
|
||||
});
|
||||
|
||||
expect(result.current.manuallyExpandedDays.has("2024-01-01")).toBe(false);
|
||||
});
|
||||
|
||||
it("saves to localStorage when toggling with userId", () => {
|
||||
const { result } = renderHook(() => useCollapsedDays(1));
|
||||
|
||||
act(() => {
|
||||
result.current.toggleDayCollapse("2024-01-01", false);
|
||||
});
|
||||
|
||||
expect(window.localStorage.setItem).toHaveBeenCalledWith("collapsedDays_user_1", expect.any(String));
|
||||
});
|
||||
|
||||
it("does not save to localStorage without userId", () => {
|
||||
const { result } = renderHook(() => useCollapsedDays(undefined));
|
||||
|
||||
act(() => {
|
||||
result.current.toggleDayCollapse("2024-01-01", false);
|
||||
});
|
||||
|
||||
expect(window.localStorage.setItem).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,246 +1,186 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { renderHook, act, waitFor } from '@testing-library/react';
|
||||
import { useDoses } from '../../hooks/useDoses';
|
||||
import { act, renderHook, waitFor } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { useDoses } from "../../hooks/useDoses";
|
||||
|
||||
describe('useDoses', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ doses: [] })
|
||||
});
|
||||
});
|
||||
describe("useDoses", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ doses: [] }),
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('initializes with empty state', () => {
|
||||
const { result } = renderHook(() => useDoses());
|
||||
|
||||
expect(result.current.takenDoses.size).toBe(0);
|
||||
expect(result.current.dismissedDoses.size).toBe(0);
|
||||
expect(result.current.clearingMissed).toBe(false);
|
||||
expect(result.current.showClearMissedConfirm).toBe(false);
|
||||
});
|
||||
it("initializes with empty state", () => {
|
||||
const { result } = renderHook(() => useDoses());
|
||||
|
||||
it('loads taken doses from API on mount', async () => {
|
||||
const mockDoses = {
|
||||
doses: [
|
||||
{ doseId: 'dose-1', dismissed: false },
|
||||
{ doseId: 'dose-2', dismissed: true }
|
||||
]
|
||||
};
|
||||
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockDoses)
|
||||
});
|
||||
expect(result.current.takenDoses.size).toBe(0);
|
||||
expect(result.current.dismissedDoses.size).toBe(0);
|
||||
expect(result.current.showClearMissedConfirm).toBe(false);
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useDoses());
|
||||
it("loads taken doses from API on mount", async () => {
|
||||
const mockDoses = {
|
||||
doses: [
|
||||
{ doseId: "dose-1", dismissed: false },
|
||||
{ doseId: "dose-2", dismissed: true },
|
||||
],
|
||||
};
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.takenDoses.has('dose-1')).toBe(true);
|
||||
expect(result.current.dismissedDoses.has('dose-2')).toBe(true);
|
||||
});
|
||||
});
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockDoses),
|
||||
});
|
||||
|
||||
it('getDoseId returns correct ID format', () => {
|
||||
const { result } = renderHook(() => useDoses());
|
||||
|
||||
expect(result.current.getDoseId('dose-1', null)).toBe('dose-1');
|
||||
expect(result.current.getDoseId('dose-1', 'John')).toBe('dose-1-John');
|
||||
});
|
||||
const { result } = renderHook(() => useDoses());
|
||||
|
||||
it('countTakenDoses calculates correctly', async () => {
|
||||
const mockDoses = {
|
||||
doses: [{ doseId: 'dose-1', dismissed: false }]
|
||||
};
|
||||
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockDoses)
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(result.current.takenDoses.has("dose-1")).toBe(true);
|
||||
expect(result.current.dismissedDoses.has("dose-2")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useDoses());
|
||||
it("getDoseId returns correct ID format", () => {
|
||||
const { result } = renderHook(() => useDoses());
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.takenDoses.has('dose-1')).toBe(true);
|
||||
});
|
||||
expect(result.current.getDoseId("dose-1", null)).toBe("dose-1");
|
||||
expect(result.current.getDoseId("dose-1", "John")).toBe("dose-1-John");
|
||||
});
|
||||
|
||||
const doses = [
|
||||
{ id: 'dose-1', takenBy: [] },
|
||||
{ id: 'dose-2', takenBy: [] }
|
||||
];
|
||||
it("countTakenDoses calculates correctly", async () => {
|
||||
const mockDoses = {
|
||||
doses: [{ doseId: "dose-1", dismissed: false }],
|
||||
};
|
||||
|
||||
const count = result.current.countTakenDoses(doses);
|
||||
expect(count.total).toBe(2);
|
||||
expect(count.taken).toBe(1);
|
||||
});
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockDoses),
|
||||
});
|
||||
|
||||
it('countTakenDoses handles multiple people', async () => {
|
||||
const mockDoses = {
|
||||
doses: [
|
||||
{ doseId: 'dose-1-Alice', dismissed: false },
|
||||
{ doseId: 'dose-1-Bob', dismissed: false }
|
||||
]
|
||||
};
|
||||
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockDoses)
|
||||
});
|
||||
const { result } = renderHook(() => useDoses());
|
||||
|
||||
const { result } = renderHook(() => useDoses());
|
||||
await waitFor(() => {
|
||||
expect(result.current.takenDoses.has("dose-1")).toBe(true);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.takenDoses.size).toBe(2);
|
||||
});
|
||||
const doses = [
|
||||
{ id: "dose-1", takenBy: [] },
|
||||
{ id: "dose-2", takenBy: [] },
|
||||
];
|
||||
|
||||
const doses = [{ id: 'dose-1', takenBy: ['Alice', 'Bob', 'Charlie'] }];
|
||||
const count = result.current.countTakenDoses(doses);
|
||||
expect(count.total).toBe(3);
|
||||
expect(count.taken).toBe(2);
|
||||
});
|
||||
const count = result.current.countTakenDoses(doses);
|
||||
expect(count.total).toBe(2);
|
||||
expect(count.taken).toBe(1);
|
||||
});
|
||||
|
||||
it('marks dose as taken optimistically', async () => {
|
||||
// First call for initial load, subsequent calls for marking dose
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ doses: [] }) })
|
||||
.mockResolvedValueOnce({ ok: true });
|
||||
it("countTakenDoses handles multiple people", async () => {
|
||||
const mockDoses = {
|
||||
doses: [
|
||||
{ doseId: "dose-1-Alice", dismissed: false },
|
||||
{ doseId: "dose-1-Bob", dismissed: false },
|
||||
],
|
||||
};
|
||||
|
||||
const { result } = renderHook(() => useDoses());
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockDoses),
|
||||
});
|
||||
|
||||
// Wait for initial load to complete
|
||||
await waitFor(() => {
|
||||
expect(result.current.takenDoses.size).toBe(0);
|
||||
});
|
||||
const { result } = renderHook(() => useDoses());
|
||||
|
||||
await act(async () => {
|
||||
await result.current.markDoseTaken('new-dose');
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(result.current.takenDoses.size).toBe(2);
|
||||
});
|
||||
|
||||
expect(result.current.takenDoses.has('new-dose')).toBe(true);
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
'/api/doses/taken',
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ doseId: 'new-dose' })
|
||||
})
|
||||
);
|
||||
});
|
||||
const doses = [{ id: "dose-1", takenBy: ["Alice", "Bob", "Charlie"] }];
|
||||
const count = result.current.countTakenDoses(doses);
|
||||
expect(count.total).toBe(3);
|
||||
expect(count.taken).toBe(2);
|
||||
});
|
||||
|
||||
it('reverts optimistic update on error', async () => {
|
||||
// First call for initial load, second for marking dose fails
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ doses: [] }) })
|
||||
.mockRejectedValueOnce(new Error('Network error'));
|
||||
it("marks dose as taken optimistically", async () => {
|
||||
// First call for initial load, subsequent calls for marking dose
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ doses: [] }) })
|
||||
.mockResolvedValueOnce({ ok: true });
|
||||
|
||||
const { result } = renderHook(() => useDoses());
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.takenDoses.size).toBe(0);
|
||||
});
|
||||
const { result } = renderHook(() => useDoses());
|
||||
|
||||
await act(async () => {
|
||||
await result.current.markDoseTaken('new-dose');
|
||||
});
|
||||
// Wait for initial load to complete
|
||||
await waitFor(() => {
|
||||
expect(result.current.takenDoses.size).toBe(0);
|
||||
});
|
||||
|
||||
// After error, the dose should be removed
|
||||
await waitFor(() => {
|
||||
expect(result.current.takenDoses.has('new-dose')).toBe(false);
|
||||
});
|
||||
});
|
||||
await act(async () => {
|
||||
await result.current.markDoseTaken("new-dose");
|
||||
});
|
||||
|
||||
it('undoes dose taken optimistically', async () => {
|
||||
const mockDoses = {
|
||||
doses: [{ doseId: 'taken-dose', dismissed: false }]
|
||||
};
|
||||
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve(mockDoses) })
|
||||
.mockResolvedValueOnce({ ok: true });
|
||||
expect(result.current.takenDoses.has("new-dose")).toBe(true);
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
"/api/doses/taken",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
body: JSON.stringify({ doseId: "new-dose" }),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useDoses());
|
||||
it("reverts optimistic update on error", async () => {
|
||||
// First call for initial load, second for marking dose fails
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ doses: [] }) })
|
||||
.mockRejectedValueOnce(new Error("Network error"));
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.takenDoses.has('taken-dose')).toBe(true);
|
||||
});
|
||||
const { result } = renderHook(() => useDoses());
|
||||
|
||||
await act(async () => {
|
||||
await result.current.undoDoseTaken('taken-dose');
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(result.current.takenDoses.size).toBe(0);
|
||||
});
|
||||
|
||||
expect(result.current.takenDoses.has('taken-dose')).toBe(false);
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
'/api/doses/taken/taken-dose',
|
||||
expect.objectContaining({ method: 'DELETE' })
|
||||
);
|
||||
});
|
||||
await act(async () => {
|
||||
await result.current.markDoseTaken("new-dose");
|
||||
});
|
||||
|
||||
it('dismisses missed doses', async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ doses: [] }) })
|
||||
.mockResolvedValueOnce({ ok: true });
|
||||
// After error, the dose should be removed
|
||||
await waitFor(() => {
|
||||
expect(result.current.takenDoses.has("new-dose")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useDoses());
|
||||
it("undoes dose taken optimistically", async () => {
|
||||
const mockDoses = {
|
||||
doses: [{ doseId: "taken-dose", dismissed: false }],
|
||||
};
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.clearingMissed).toBe(false);
|
||||
});
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve(mockDoses) })
|
||||
.mockResolvedValueOnce({ ok: true });
|
||||
|
||||
await act(async () => {
|
||||
await result.current.dismissMissedDoses(['missed-1', 'missed-2']);
|
||||
});
|
||||
const { result } = renderHook(() => useDoses());
|
||||
|
||||
expect(result.current.dismissedDoses.has('missed-1')).toBe(true);
|
||||
expect(result.current.dismissedDoses.has('missed-2')).toBe(true);
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(result.current.takenDoses.has("taken-dose")).toBe(true);
|
||||
});
|
||||
|
||||
it('does nothing when dismissing empty array', async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ doses: [] })
|
||||
});
|
||||
await act(async () => {
|
||||
await result.current.undoDoseTaken("taken-dose");
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useDoses());
|
||||
expect(result.current.takenDoses.has("taken-dose")).toBe(false);
|
||||
expect(fetch).toHaveBeenCalledWith("/api/doses/taken/taken-dose", expect.objectContaining({ method: "DELETE" }));
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.dismissMissedDoses([]);
|
||||
});
|
||||
it("setShowClearMissedConfirm works", () => {
|
||||
const { result } = renderHook(() => useDoses());
|
||||
|
||||
// Should not make a POST call for dismiss
|
||||
expect(fetch).not.toHaveBeenCalledWith(
|
||||
'/api/doses/dismiss',
|
||||
expect.anything()
|
||||
);
|
||||
});
|
||||
act(() => {
|
||||
result.current.setShowClearMissedConfirm(true);
|
||||
});
|
||||
|
||||
it('setShowClearMissedConfirm works', () => {
|
||||
const { result } = renderHook(() => useDoses());
|
||||
|
||||
act(() => {
|
||||
result.current.setShowClearMissedConfirm(true);
|
||||
});
|
||||
|
||||
expect(result.current.showClearMissedConfirm).toBe(true);
|
||||
});
|
||||
|
||||
it('handles API error on dismiss gracefully', async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({ doses: [] }) })
|
||||
.mockRejectedValueOnce(new Error('Network error'));
|
||||
|
||||
const { result } = renderHook(() => useDoses());
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.clearingMissed).toBe(false);
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.dismissMissedDoses(['missed-1']);
|
||||
});
|
||||
|
||||
expect(result.current.clearingMissed).toBe(false);
|
||||
});
|
||||
expect(result.current.showClearMissedConfirm).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,74 +1,74 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { defaultForm, defaultBlister } from '../../hooks/useMedicationForm';
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { defaultBlister, defaultForm } from "../../hooks/useMedicationForm";
|
||||
|
||||
// Note: Hook tests were causing memory issues due to complex dependencies
|
||||
// Testing only the exported utility functions to avoid heap overflow
|
||||
|
||||
describe('defaultBlister', () => {
|
||||
it('creates a blister with default values', () => {
|
||||
const blister = defaultBlister();
|
||||
expect(blister.usage).toBe('1');
|
||||
expect(blister.every).toBe('1');
|
||||
expect(blister.startDate).toMatch(/^\d{4}-\d{2}-\d{2}$/);
|
||||
expect(blister.startTime).toMatch(/^\d{2}:\d{2}$/);
|
||||
});
|
||||
describe("defaultBlister", () => {
|
||||
it("creates a blister with default values", () => {
|
||||
const blister = defaultBlister();
|
||||
expect(blister.usage).toBe("1");
|
||||
expect(blister.every).toBe("1");
|
||||
expect(blister.startDate).toMatch(/^\d{4}-\d{2}-\d{2}$/);
|
||||
expect(blister.startTime).toMatch(/^\d{2}:\d{2}$/);
|
||||
});
|
||||
|
||||
it('uses current date', () => {
|
||||
const before = new Date();
|
||||
const blister = defaultBlister();
|
||||
const after = new Date();
|
||||
|
||||
const blisterDate = new Date(blister.startDate);
|
||||
expect(blisterDate >= new Date(before.toISOString().slice(0, 10))).toBe(true);
|
||||
expect(blisterDate <= new Date(after.toISOString().slice(0, 10) + 'T23:59:59')).toBe(true);
|
||||
});
|
||||
it("uses current date", () => {
|
||||
const before = new Date();
|
||||
const blister = defaultBlister();
|
||||
const after = new Date();
|
||||
|
||||
const blisterDate = new Date(blister.startDate);
|
||||
expect(blisterDate >= new Date(before.toISOString().slice(0, 10))).toBe(true);
|
||||
expect(blisterDate <= new Date(`${after.toISOString().slice(0, 10)}T23:59:59`)).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe('defaultForm', () => {
|
||||
it('creates a form with default values', () => {
|
||||
const form = defaultForm();
|
||||
expect(form.name).toBe('');
|
||||
expect(form.genericName).toBe('');
|
||||
expect(form.takenBy).toEqual([]);
|
||||
expect(form.packCount).toBe('1');
|
||||
expect(form.blistersPerPack).toBe('1');
|
||||
expect(form.pillsPerBlister).toBe('1');
|
||||
expect(form.looseTablets).toBe('0');
|
||||
expect(form.pillWeightMg).toBe('');
|
||||
expect(form.expiryDate).toBe('');
|
||||
expect(form.notes).toBe('');
|
||||
expect(form.intakeRemindersEnabled).toBe(false);
|
||||
expect(form.blisters).toHaveLength(1);
|
||||
});
|
||||
describe("defaultForm", () => {
|
||||
it("creates a form with default values", () => {
|
||||
const form = defaultForm();
|
||||
expect(form.name).toBe("");
|
||||
expect(form.genericName).toBe("");
|
||||
expect(form.takenBy).toEqual([]);
|
||||
expect(form.packCount).toBe("1");
|
||||
expect(form.blistersPerPack).toBe("1");
|
||||
expect(form.pillsPerBlister).toBe("1");
|
||||
expect(form.looseTablets).toBe("0");
|
||||
expect(form.pillWeightMg).toBe("");
|
||||
expect(form.expiryDate).toBe("");
|
||||
expect(form.notes).toBe("");
|
||||
expect(form.intakeRemindersEnabled).toBe(false);
|
||||
expect(form.blisters).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('creates a blister in the form', () => {
|
||||
const form = defaultForm();
|
||||
expect(form.blisters).toHaveLength(1);
|
||||
expect(form.blisters[0].usage).toBe('1');
|
||||
expect(form.blisters[0].every).toBe('1');
|
||||
});
|
||||
it("creates a blister in the form", () => {
|
||||
const form = defaultForm();
|
||||
expect(form.blisters).toHaveLength(1);
|
||||
expect(form.blisters[0].usage).toBe("1");
|
||||
expect(form.blisters[0].every).toBe("1");
|
||||
});
|
||||
|
||||
it('creates independent forms', () => {
|
||||
const form1 = defaultForm();
|
||||
const form2 = defaultForm();
|
||||
|
||||
form1.name = 'Test';
|
||||
expect(form2.name).toBe('');
|
||||
});
|
||||
it("creates independent forms", () => {
|
||||
const form1 = defaultForm();
|
||||
const form2 = defaultForm();
|
||||
|
||||
it('creates independent blisters arrays', () => {
|
||||
const form1 = defaultForm();
|
||||
const form2 = defaultForm();
|
||||
|
||||
form1.blisters.push(defaultBlister());
|
||||
expect(form2.blisters).toHaveLength(1);
|
||||
});
|
||||
form1.name = "Test";
|
||||
expect(form2.name).toBe("");
|
||||
});
|
||||
|
||||
it('creates independent takenBy arrays', () => {
|
||||
const form1 = defaultForm();
|
||||
const form2 = defaultForm();
|
||||
|
||||
form1.takenBy.push('John');
|
||||
expect(form2.takenBy).toHaveLength(0);
|
||||
});
|
||||
it("creates independent blisters arrays", () => {
|
||||
const form1 = defaultForm();
|
||||
const form2 = defaultForm();
|
||||
|
||||
form1.blisters.push(defaultBlister());
|
||||
expect(form2.blisters).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("creates independent takenBy arrays", () => {
|
||||
const form1 = defaultForm();
|
||||
const form2 = defaultForm();
|
||||
|
||||
form1.takenBy.push("John");
|
||||
expect(form2.takenBy).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,197 +1,195 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { renderHook, act, waitFor } from '@testing-library/react';
|
||||
import { useMedications } from '../../hooks/useMedications';
|
||||
import { act, renderHook, waitFor } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { useMedications } from "../../hooks/useMedications";
|
||||
|
||||
describe('useMedications', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve([])
|
||||
});
|
||||
});
|
||||
describe("useMedications", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve([]),
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('initializes with empty state', () => {
|
||||
const { result } = renderHook(() => useMedications());
|
||||
|
||||
expect(result.current.meds).toEqual([]);
|
||||
expect(result.current.loading).toBe(false);
|
||||
expect(result.current.saving).toBe(false);
|
||||
expect(result.current.uploadingImage).toBe(false);
|
||||
});
|
||||
it("initializes with empty state", () => {
|
||||
const { result } = renderHook(() => useMedications());
|
||||
|
||||
it('loads medications from API', async () => {
|
||||
const mockMeds = [
|
||||
{ id: 1, name: 'TestMed', packCount: 1 }
|
||||
];
|
||||
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockMeds)
|
||||
});
|
||||
expect(result.current.meds).toEqual([]);
|
||||
expect(result.current.loading).toBe(false);
|
||||
expect(result.current.saving).toBe(false);
|
||||
expect(result.current.uploadingImage).toBe(false);
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useMedications());
|
||||
it("loads medications from API", async () => {
|
||||
const mockMeds = [{ id: 1, name: "TestMed", packCount: 1 }];
|
||||
|
||||
act(() => {
|
||||
result.current.loadMeds();
|
||||
});
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockMeds),
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.meds).toEqual(mockMeds);
|
||||
});
|
||||
|
||||
expect(fetch).toHaveBeenCalledWith('/api/medications');
|
||||
});
|
||||
const { result } = renderHook(() => useMedications());
|
||||
|
||||
it('handles API error gracefully', async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error('Network error'));
|
||||
act(() => {
|
||||
result.current.loadMeds();
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useMedications());
|
||||
await waitFor(() => {
|
||||
expect(result.current.meds).toEqual(mockMeds);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.loadMeds();
|
||||
});
|
||||
expect(fetch).toHaveBeenCalledWith("/api/medications");
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.loading).toBe(false);
|
||||
});
|
||||
|
||||
expect(result.current.meds).toEqual([]);
|
||||
});
|
||||
it("handles API error gracefully", async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error("Network error"));
|
||||
|
||||
it('handles non-array response', async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ not: 'array' })
|
||||
});
|
||||
const { result } = renderHook(() => useMedications());
|
||||
|
||||
const { result } = renderHook(() => useMedications());
|
||||
act(() => {
|
||||
result.current.loadMeds();
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.loadMeds();
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(result.current.loading).toBe(false);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.loading).toBe(false);
|
||||
});
|
||||
|
||||
expect(result.current.meds).toEqual([]);
|
||||
});
|
||||
expect(result.current.meds).toEqual([]);
|
||||
});
|
||||
|
||||
it('deletes medication', async () => {
|
||||
const mockMeds = [{ id: 1, name: 'TestMed' }];
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve(mockMeds) })
|
||||
.mockResolvedValueOnce({ ok: true })
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve([]) });
|
||||
it("handles non-array response", async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ not: "array" }),
|
||||
});
|
||||
|
||||
const mockResetForm = vi.fn();
|
||||
const { result } = renderHook(() => useMedications());
|
||||
const { result } = renderHook(() => useMedications());
|
||||
|
||||
// First load meds
|
||||
act(() => {
|
||||
result.current.loadMeds();
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.meds).toEqual(mockMeds);
|
||||
});
|
||||
act(() => {
|
||||
result.current.loadMeds();
|
||||
});
|
||||
|
||||
// Then delete
|
||||
await act(async () => {
|
||||
await result.current.deleteMed(1, 1, mockResetForm);
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(result.current.loading).toBe(false);
|
||||
});
|
||||
|
||||
expect(fetch).toHaveBeenCalledWith('/api/medications/1', { method: 'DELETE' });
|
||||
expect(mockResetForm).toHaveBeenCalled();
|
||||
});
|
||||
expect(result.current.meds).toEqual([]);
|
||||
});
|
||||
|
||||
it('does not call resetForm if editingId does not match', async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true })
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve([]) });
|
||||
it("deletes medication", async () => {
|
||||
const mockMeds = [{ id: 1, name: "TestMed" }];
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve(mockMeds) })
|
||||
.mockResolvedValueOnce({ ok: true })
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve([]) });
|
||||
|
||||
const mockResetForm = vi.fn();
|
||||
const { result } = renderHook(() => useMedications());
|
||||
const mockResetForm = vi.fn();
|
||||
const { result } = renderHook(() => useMedications());
|
||||
|
||||
await act(async () => {
|
||||
await result.current.deleteMed(1, 2, mockResetForm);
|
||||
});
|
||||
// First load meds
|
||||
act(() => {
|
||||
result.current.loadMeds();
|
||||
});
|
||||
|
||||
expect(mockResetForm).not.toHaveBeenCalled();
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(result.current.meds).toEqual(mockMeds);
|
||||
});
|
||||
|
||||
it('uploads medication image', async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true })
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve([]) });
|
||||
// Then delete
|
||||
await act(async () => {
|
||||
await result.current.deleteMed(1, 1, mockResetForm);
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useMedications());
|
||||
const file = new File(['test'], 'test.jpg', { type: 'image/jpeg' });
|
||||
expect(fetch).toHaveBeenCalledWith("/api/medications/1", { method: "DELETE" });
|
||||
expect(mockResetForm).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.uploadMedImage(1, file);
|
||||
});
|
||||
it("does not call resetForm if editingId does not match", async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true })
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve([]) });
|
||||
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
'/api/medications/1/image',
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
body: expect.any(FormData)
|
||||
})
|
||||
);
|
||||
});
|
||||
const mockResetForm = vi.fn();
|
||||
const { result } = renderHook(() => useMedications());
|
||||
|
||||
it('handles image upload error', async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error('Upload failed'));
|
||||
await act(async () => {
|
||||
await result.current.deleteMed(1, 2, mockResetForm);
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useMedications());
|
||||
const file = new File(['test'], 'test.jpg', { type: 'image/jpeg' });
|
||||
expect(mockResetForm).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.uploadMedImage(1, file);
|
||||
});
|
||||
it("uploads medication image", async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true })
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve([]) });
|
||||
|
||||
expect(result.current.uploadingImage).toBe(false);
|
||||
});
|
||||
const { result } = renderHook(() => useMedications());
|
||||
const file = new File(["test"], "test.jpg", { type: "image/jpeg" });
|
||||
|
||||
it('deletes medication image', async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true })
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve([]) });
|
||||
await act(async () => {
|
||||
await result.current.uploadMedImage(1, file);
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useMedications());
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
"/api/medications/1/image",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
body: expect.any(FormData),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.deleteMedImage(1);
|
||||
});
|
||||
it("handles image upload error", async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error("Upload failed"));
|
||||
|
||||
expect(fetch).toHaveBeenCalledWith('/api/medications/1/image', { method: 'DELETE' });
|
||||
});
|
||||
const { result } = renderHook(() => useMedications());
|
||||
const file = new File(["test"], "test.jpg", { type: "image/jpeg" });
|
||||
|
||||
it('allows setting meds directly', () => {
|
||||
const { result } = renderHook(() => useMedications());
|
||||
|
||||
const newMeds = [{ id: 1, name: 'NewMed' }] as any;
|
||||
|
||||
act(() => {
|
||||
result.current.setMeds(newMeds);
|
||||
});
|
||||
|
||||
expect(result.current.meds).toEqual(newMeds);
|
||||
});
|
||||
await act(async () => {
|
||||
await result.current.uploadMedImage(1, file);
|
||||
});
|
||||
|
||||
it('allows setting saving state', () => {
|
||||
const { result } = renderHook(() => useMedications());
|
||||
|
||||
act(() => {
|
||||
result.current.setSaving(true);
|
||||
});
|
||||
|
||||
expect(result.current.saving).toBe(true);
|
||||
});
|
||||
expect(result.current.uploadingImage).toBe(false);
|
||||
});
|
||||
|
||||
it("deletes medication image", async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true })
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve([]) });
|
||||
|
||||
const { result } = renderHook(() => useMedications());
|
||||
|
||||
await act(async () => {
|
||||
await result.current.deleteMedImage(1);
|
||||
});
|
||||
|
||||
expect(fetch).toHaveBeenCalledWith("/api/medications/1/image", { method: "DELETE" });
|
||||
});
|
||||
|
||||
it("allows setting meds directly", () => {
|
||||
const { result } = renderHook(() => useMedications());
|
||||
|
||||
const newMeds = [{ id: 1, name: "NewMed" }] as any;
|
||||
|
||||
act(() => {
|
||||
result.current.setMeds(newMeds);
|
||||
});
|
||||
|
||||
expect(result.current.meds).toEqual(newMeds);
|
||||
});
|
||||
|
||||
it("allows setting saving state", () => {
|
||||
const { result } = renderHook(() => useMedications());
|
||||
|
||||
act(() => {
|
||||
result.current.setSaving(true);
|
||||
});
|
||||
|
||||
expect(result.current.saving).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,313 +1,311 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { renderHook, act, waitFor } from '@testing-library/react';
|
||||
import { useRefill } from '../../hooks/useRefill';
|
||||
import type { Medication, Coverage } from '../../types';
|
||||
import { act, renderHook } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { useRefill } from "../../hooks/useRefill";
|
||||
import type { Coverage, Medication } from "../../types";
|
||||
|
||||
describe('useRefill', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({})
|
||||
});
|
||||
vi.spyOn(window.history, 'pushState').mockImplementation(() => {});
|
||||
vi.spyOn(window.history, 'back').mockImplementation(() => {});
|
||||
});
|
||||
describe("useRefill", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({}),
|
||||
});
|
||||
vi.spyOn(window.history, "pushState").mockImplementation(() => {});
|
||||
vi.spyOn(window.history, "back").mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it('initializes with default state', () => {
|
||||
const { result } = renderHook(() => useRefill());
|
||||
|
||||
expect(result.current.showRefillModal).toBe(false);
|
||||
expect(result.current.refillPacks).toBe(1);
|
||||
expect(result.current.refillLoose).toBe(0);
|
||||
expect(result.current.refillSaving).toBe(false);
|
||||
expect(result.current.refillHistory).toEqual([]);
|
||||
expect(result.current.refillHistoryExpanded).toBe(false);
|
||||
expect(result.current.showEditStockModal).toBe(false);
|
||||
});
|
||||
it("initializes with default state", () => {
|
||||
const { result } = renderHook(() => useRefill());
|
||||
|
||||
it('loads refill history', async () => {
|
||||
const mockHistory = [
|
||||
{ id: 1, packsAdded: 2, loosePillsAdded: 0, createdAt: '2024-03-15T10:00:00Z' }
|
||||
];
|
||||
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockHistory)
|
||||
});
|
||||
expect(result.current.showRefillModal).toBe(false);
|
||||
expect(result.current.refillPacks).toBe(1);
|
||||
expect(result.current.refillLoose).toBe(0);
|
||||
expect(result.current.refillSaving).toBe(false);
|
||||
expect(result.current.refillHistory).toEqual([]);
|
||||
expect(result.current.refillHistoryExpanded).toBe(false);
|
||||
expect(result.current.showEditStockModal).toBe(false);
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useRefill());
|
||||
it("loads refill history", async () => {
|
||||
const mockHistory = [{ id: 1, packsAdded: 2, loosePillsAdded: 0, createdAt: "2024-03-15T10:00:00Z" }];
|
||||
|
||||
await act(async () => {
|
||||
await result.current.loadRefillHistory(1);
|
||||
});
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockHistory),
|
||||
});
|
||||
|
||||
expect(result.current.refillHistory).toEqual(mockHistory);
|
||||
});
|
||||
const { result } = renderHook(() => useRefill());
|
||||
|
||||
it('handles refill history with refills wrapper', async () => {
|
||||
const mockHistory = {
|
||||
refills: [{ id: 1, packsAdded: 2, createdAt: '2024-03-15T10:00:00Z' }]
|
||||
};
|
||||
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockHistory)
|
||||
});
|
||||
await act(async () => {
|
||||
await result.current.loadRefillHistory(1);
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useRefill());
|
||||
expect(result.current.refillHistory).toEqual(mockHistory);
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.loadRefillHistory(1);
|
||||
});
|
||||
it("handles refill history with refills wrapper", async () => {
|
||||
const mockHistory = {
|
||||
refills: [{ id: 1, packsAdded: 2, createdAt: "2024-03-15T10:00:00Z" }],
|
||||
};
|
||||
|
||||
expect(result.current.refillHistory).toEqual(mockHistory.refills);
|
||||
});
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockHistory),
|
||||
});
|
||||
|
||||
it('handles refill history error', async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error('Network error'));
|
||||
const { result } = renderHook(() => useRefill());
|
||||
|
||||
const { result } = renderHook(() => useRefill());
|
||||
await act(async () => {
|
||||
await result.current.loadRefillHistory(1);
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.loadRefillHistory(1);
|
||||
});
|
||||
expect(result.current.refillHistory).toEqual(mockHistory.refills);
|
||||
});
|
||||
|
||||
expect(result.current.refillHistory).toEqual([]);
|
||||
});
|
||||
it("handles refill history error", async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error("Network error"));
|
||||
|
||||
it('opens refill modal and pushes history', () => {
|
||||
const { result } = renderHook(() => useRefill());
|
||||
|
||||
act(() => {
|
||||
result.current.openRefillModal();
|
||||
});
|
||||
const { result } = renderHook(() => useRefill());
|
||||
|
||||
expect(result.current.showRefillModal).toBe(true);
|
||||
expect(window.history.pushState).toHaveBeenCalledWith({ modal: 'refill' }, '');
|
||||
});
|
||||
await act(async () => {
|
||||
await result.current.loadRefillHistory(1);
|
||||
});
|
||||
|
||||
it('closes refill modal using history back', () => {
|
||||
const { result } = renderHook(() => useRefill());
|
||||
|
||||
act(() => {
|
||||
result.current.openRefillModal();
|
||||
});
|
||||
expect(result.current.refillHistory).toEqual([]);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.closeRefillModal();
|
||||
});
|
||||
it("opens refill modal and pushes history", () => {
|
||||
const { result } = renderHook(() => useRefill());
|
||||
|
||||
expect(window.history.back).toHaveBeenCalled();
|
||||
});
|
||||
act(() => {
|
||||
result.current.openRefillModal();
|
||||
});
|
||||
|
||||
it('does not call history back when refill modal not open', () => {
|
||||
const { result } = renderHook(() => useRefill());
|
||||
|
||||
act(() => {
|
||||
result.current.closeRefillModal();
|
||||
});
|
||||
expect(result.current.showRefillModal).toBe(true);
|
||||
expect(window.history.pushState).toHaveBeenCalledWith({ modal: "refill" }, "");
|
||||
});
|
||||
|
||||
expect(window.history.back).not.toHaveBeenCalled();
|
||||
});
|
||||
it("closes refill modal using history back", () => {
|
||||
const { result } = renderHook(() => useRefill());
|
||||
|
||||
it('submits refill successfully', async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ newStock: { packCount: 3, looseTablets: 5 } })
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve([])
|
||||
});
|
||||
act(() => {
|
||||
result.current.openRefillModal();
|
||||
});
|
||||
|
||||
const mockSetForm = vi.fn();
|
||||
const mockLoadMeds = vi.fn();
|
||||
|
||||
const { result } = renderHook(() => useRefill());
|
||||
act(() => {
|
||||
result.current.closeRefillModal();
|
||||
});
|
||||
|
||||
// Open modal first
|
||||
act(() => {
|
||||
result.current.openRefillModal();
|
||||
});
|
||||
expect(window.history.back).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.submitRefill(1, 1, mockSetForm, mockLoadMeds);
|
||||
});
|
||||
it("does not call history back when refill modal not open", () => {
|
||||
const { result } = renderHook(() => useRefill());
|
||||
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
'/api/medications/1/refill',
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ packsAdded: 1, loosePillsAdded: 0 })
|
||||
})
|
||||
);
|
||||
expect(mockSetForm).toHaveBeenCalled();
|
||||
expect(mockLoadMeds).toHaveBeenCalled();
|
||||
});
|
||||
act(() => {
|
||||
result.current.closeRefillModal();
|
||||
});
|
||||
|
||||
it('does not submit refill if both values are 0', async () => {
|
||||
const { result } = renderHook(() => useRefill());
|
||||
|
||||
act(() => {
|
||||
result.current.setRefillPacks(0);
|
||||
result.current.setRefillLoose(0);
|
||||
});
|
||||
expect(window.history.back).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
const mockSetForm = vi.fn();
|
||||
const mockLoadMeds = vi.fn();
|
||||
it("submits refill successfully", async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ newStock: { packCount: 3, looseTablets: 5 } }),
|
||||
})
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve([]),
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.submitRefill(1, 1, mockSetForm, mockLoadMeds);
|
||||
});
|
||||
const mockSetForm = vi.fn();
|
||||
const mockLoadMeds = vi.fn();
|
||||
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
const { result } = renderHook(() => useRefill());
|
||||
|
||||
it('opens edit stock modal', () => {
|
||||
const { result } = renderHook(() => useRefill());
|
||||
|
||||
const mockMed: Medication = {
|
||||
id: 1,
|
||||
name: 'Test Med',
|
||||
packCount: 1,
|
||||
blistersPerPack: 2,
|
||||
pillsPerBlister: 10,
|
||||
looseTablets: 5,
|
||||
takenBy: [],
|
||||
blisters: [],
|
||||
updatedAt: null
|
||||
};
|
||||
// Open modal first
|
||||
act(() => {
|
||||
result.current.openRefillModal();
|
||||
});
|
||||
|
||||
const mockCoverage = {
|
||||
all: [{ name: 'Test Med', medsLeft: 20, daysLeft: 10 }] as Coverage[]
|
||||
};
|
||||
await act(async () => {
|
||||
await result.current.submitRefill(1, 1, mockSetForm, mockLoadMeds);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.openEditStockModal(mockMed, mockCoverage);
|
||||
});
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
"/api/medications/1/refill",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
body: JSON.stringify({ packsAdded: 1, loosePillsAdded: 0 }),
|
||||
})
|
||||
);
|
||||
expect(mockSetForm).toHaveBeenCalled();
|
||||
expect(mockLoadMeds).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
expect(result.current.showEditStockModal).toBe(true);
|
||||
expect(window.history.pushState).toHaveBeenCalledWith({ modal: 'editStock' }, '');
|
||||
expect(result.current.editStockFullBlisters).toBe(2); // 20 / 10 = 2
|
||||
expect(result.current.editStockPartialBlisterPills).toBe(0); // 20 % 10 = 0
|
||||
});
|
||||
it("does not submit refill if both values are 0", async () => {
|
||||
const { result } = renderHook(() => useRefill());
|
||||
|
||||
it('closes edit stock modal using history back', () => {
|
||||
const { result } = renderHook(() => useRefill());
|
||||
|
||||
const mockMed: Medication = {
|
||||
id: 1,
|
||||
name: 'Test Med',
|
||||
packCount: 1,
|
||||
blistersPerPack: 2,
|
||||
pillsPerBlister: 10,
|
||||
looseTablets: 5,
|
||||
takenBy: [],
|
||||
blisters: [],
|
||||
updatedAt: null
|
||||
};
|
||||
act(() => {
|
||||
result.current.setRefillPacks(0);
|
||||
result.current.setRefillLoose(0);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.openEditStockModal(mockMed, { all: [] });
|
||||
});
|
||||
const mockSetForm = vi.fn();
|
||||
const mockLoadMeds = vi.fn();
|
||||
|
||||
act(() => {
|
||||
result.current.closeEditStockModal();
|
||||
});
|
||||
await act(async () => {
|
||||
await result.current.submitRefill(1, 1, mockSetForm, mockLoadMeds);
|
||||
});
|
||||
|
||||
expect(window.history.back).toHaveBeenCalled();
|
||||
});
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('submits stock correction', async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({ ok: true });
|
||||
it("opens edit stock modal", () => {
|
||||
const { result } = renderHook(() => useRefill());
|
||||
|
||||
const mockMed: Medication = {
|
||||
id: 1,
|
||||
name: 'Test Med',
|
||||
packCount: 1,
|
||||
blistersPerPack: 2,
|
||||
pillsPerBlister: 10,
|
||||
looseTablets: 5,
|
||||
takenBy: [],
|
||||
blisters: [],
|
||||
updatedAt: null
|
||||
};
|
||||
const mockMed: Medication = {
|
||||
id: 1,
|
||||
name: "Test Med",
|
||||
packCount: 1,
|
||||
blistersPerPack: 2,
|
||||
pillsPerBlister: 10,
|
||||
looseTablets: 5,
|
||||
takenBy: [],
|
||||
blisters: [],
|
||||
updatedAt: null,
|
||||
};
|
||||
|
||||
const mockLoadMeds = vi.fn();
|
||||
const { result } = renderHook(() => useRefill());
|
||||
const mockCoverage = {
|
||||
all: [{ name: "Test Med", medsLeft: 20, daysLeft: 10 }] as Coverage[],
|
||||
};
|
||||
|
||||
act(() => {
|
||||
result.current.openEditStockModal(mockMed, { all: [] });
|
||||
});
|
||||
act(() => {
|
||||
result.current.openEditStockModal(mockMed, mockCoverage);
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.submitStockCorrection(1, mockMed, mockLoadMeds);
|
||||
});
|
||||
expect(result.current.showEditStockModal).toBe(true);
|
||||
expect(window.history.pushState).toHaveBeenCalledWith({ modal: "editStock" }, "");
|
||||
expect(result.current.editStockFullBlisters).toBe(2); // 20 / 10 = 2
|
||||
expect(result.current.editStockPartialBlisterPills).toBe(0); // 20 % 10 = 0
|
||||
});
|
||||
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
'/api/medications/1/stock-adjustment',
|
||||
expect.objectContaining({ method: 'PATCH' })
|
||||
);
|
||||
expect(mockLoadMeds).toHaveBeenCalled();
|
||||
});
|
||||
it("closes edit stock modal using history back", () => {
|
||||
const { result } = renderHook(() => useRefill());
|
||||
|
||||
it('handles full blister conversion in stock correction', async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({ ok: true });
|
||||
const mockMed: Medication = {
|
||||
id: 1,
|
||||
name: "Test Med",
|
||||
packCount: 1,
|
||||
blistersPerPack: 2,
|
||||
pillsPerBlister: 10,
|
||||
looseTablets: 5,
|
||||
takenBy: [],
|
||||
blisters: [],
|
||||
updatedAt: null,
|
||||
};
|
||||
|
||||
const mockMed: Medication = {
|
||||
id: 1,
|
||||
name: 'Test Med',
|
||||
packCount: 1,
|
||||
blistersPerPack: 2,
|
||||
pillsPerBlister: 10,
|
||||
looseTablets: 5,
|
||||
takenBy: [],
|
||||
blisters: [],
|
||||
updatedAt: null
|
||||
};
|
||||
act(() => {
|
||||
result.current.openEditStockModal(mockMed, { all: [] });
|
||||
});
|
||||
|
||||
const mockLoadMeds = vi.fn();
|
||||
const { result } = renderHook(() => useRefill());
|
||||
act(() => {
|
||||
result.current.closeEditStockModal();
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.openEditStockModal(mockMed, { all: [] });
|
||||
// Set partial pills to equal a full blister
|
||||
result.current.setEditStockPartialBlisterPills(10);
|
||||
});
|
||||
expect(window.history.back).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.submitStockCorrection(1, mockMed, mockLoadMeds);
|
||||
});
|
||||
it("submits stock correction", async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({ ok: true });
|
||||
|
||||
expect(fetch).toHaveBeenCalled();
|
||||
expect(mockLoadMeds).toHaveBeenCalled();
|
||||
});
|
||||
const mockMed: Medication = {
|
||||
id: 1,
|
||||
name: "Test Med",
|
||||
packCount: 1,
|
||||
blistersPerPack: 2,
|
||||
pillsPerBlister: 10,
|
||||
looseTablets: 5,
|
||||
takenBy: [],
|
||||
blisters: [],
|
||||
updatedAt: null,
|
||||
};
|
||||
|
||||
it('allows setting state directly', () => {
|
||||
const { result } = renderHook(() => useRefill());
|
||||
|
||||
act(() => {
|
||||
result.current.setRefillPacks(5);
|
||||
result.current.setRefillLoose(3);
|
||||
result.current.setRefillHistoryExpanded(true);
|
||||
result.current.setShowRefillModal(true);
|
||||
result.current.setShowEditStockModal(true);
|
||||
result.current.setEditStockFullBlisters(10);
|
||||
result.current.setEditStockPartialBlisterPills(5);
|
||||
});
|
||||
const mockLoadMeds = vi.fn();
|
||||
const { result } = renderHook(() => useRefill());
|
||||
|
||||
expect(result.current.refillPacks).toBe(5);
|
||||
expect(result.current.refillLoose).toBe(3);
|
||||
expect(result.current.refillHistoryExpanded).toBe(true);
|
||||
expect(result.current.showRefillModal).toBe(true);
|
||||
expect(result.current.showEditStockModal).toBe(true);
|
||||
expect(result.current.editStockFullBlisters).toBe(10);
|
||||
expect(result.current.editStockPartialBlisterPills).toBe(5);
|
||||
});
|
||||
act(() => {
|
||||
result.current.openEditStockModal(mockMed, { all: [] });
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.submitStockCorrection(1, mockMed, mockLoadMeds);
|
||||
});
|
||||
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
"/api/medications/1/stock-adjustment",
|
||||
expect.objectContaining({ method: "PATCH" })
|
||||
);
|
||||
expect(mockLoadMeds).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("handles full blister conversion in stock correction", async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({ ok: true });
|
||||
|
||||
const mockMed: Medication = {
|
||||
id: 1,
|
||||
name: "Test Med",
|
||||
packCount: 1,
|
||||
blistersPerPack: 2,
|
||||
pillsPerBlister: 10,
|
||||
looseTablets: 5,
|
||||
takenBy: [],
|
||||
blisters: [],
|
||||
updatedAt: null,
|
||||
};
|
||||
|
||||
const mockLoadMeds = vi.fn();
|
||||
const { result } = renderHook(() => useRefill());
|
||||
|
||||
act(() => {
|
||||
result.current.openEditStockModal(mockMed, { all: [] });
|
||||
// Set partial pills to equal a full blister
|
||||
result.current.setEditStockPartialBlisterPills(10);
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.submitStockCorrection(1, mockMed, mockLoadMeds);
|
||||
});
|
||||
|
||||
expect(fetch).toHaveBeenCalled();
|
||||
expect(mockLoadMeds).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("allows setting state directly", () => {
|
||||
const { result } = renderHook(() => useRefill());
|
||||
|
||||
act(() => {
|
||||
result.current.setRefillPacks(5);
|
||||
result.current.setRefillLoose(3);
|
||||
result.current.setRefillHistoryExpanded(true);
|
||||
result.current.setShowRefillModal(true);
|
||||
result.current.setShowEditStockModal(true);
|
||||
result.current.setEditStockFullBlisters(10);
|
||||
result.current.setEditStockPartialBlisterPills(5);
|
||||
});
|
||||
|
||||
expect(result.current.refillPacks).toBe(5);
|
||||
expect(result.current.refillLoose).toBe(3);
|
||||
expect(result.current.refillHistoryExpanded).toBe(true);
|
||||
expect(result.current.showRefillModal).toBe(true);
|
||||
expect(result.current.showEditStockModal).toBe(true);
|
||||
expect(result.current.editStockFullBlisters).toBe(10);
|
||||
expect(result.current.editStockPartialBlisterPills).toBe(5);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,252 +1,252 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { renderHook, act, waitFor } from '@testing-library/react';
|
||||
import { useSettings } from '../../hooks/useSettings';
|
||||
import React from 'react';
|
||||
import { act, renderHook, waitFor } from "@testing-library/react";
|
||||
import type React from "react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { useSettings } from "../../hooks/useSettings";
|
||||
|
||||
describe('useSettings', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({})
|
||||
});
|
||||
});
|
||||
describe("useSettings", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({}),
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('initializes with default settings', () => {
|
||||
const { result } = renderHook(() => useSettings());
|
||||
|
||||
expect(result.current.settings.emailEnabled).toBe(false);
|
||||
expect(result.current.settings.lowStockDays).toBe(30);
|
||||
expect(result.current.settings.reminderDaysBefore).toBe(7);
|
||||
expect(result.current.settingsLoading).toBe(true);
|
||||
});
|
||||
it("initializes with default settings", () => {
|
||||
const { result } = renderHook(() => useSettings());
|
||||
|
||||
it('loads settings from API on mount', async () => {
|
||||
const mockSettings = {
|
||||
emailEnabled: true,
|
||||
notificationEmail: 'test@example.com',
|
||||
lowStockDays: 14
|
||||
};
|
||||
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockSettings)
|
||||
});
|
||||
expect(result.current.settings.emailEnabled).toBe(false);
|
||||
expect(result.current.settings.lowStockDays).toBe(30);
|
||||
expect(result.current.settings.reminderDaysBefore).toBe(7);
|
||||
expect(result.current.settingsLoading).toBe(true);
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useSettings());
|
||||
it("loads settings from API on mount", async () => {
|
||||
const mockSettings = {
|
||||
emailEnabled: true,
|
||||
notificationEmail: "test@example.com",
|
||||
lowStockDays: 14,
|
||||
};
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settingsLoading).toBe(false);
|
||||
});
|
||||
|
||||
expect(result.current.settings.emailEnabled).toBe(true);
|
||||
expect(result.current.settings.notificationEmail).toBe('test@example.com');
|
||||
});
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve(mockSettings),
|
||||
});
|
||||
|
||||
it('handles API error on load', async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error('Network error'));
|
||||
const { result } = renderHook(() => useSettings());
|
||||
|
||||
const { result } = renderHook(() => useSettings());
|
||||
await waitFor(() => {
|
||||
expect(result.current.settingsLoading).toBe(false);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settingsLoading).toBe(false);
|
||||
});
|
||||
});
|
||||
expect(result.current.settings.emailEnabled).toBe(true);
|
||||
expect(result.current.settings.notificationEmail).toBe("test@example.com");
|
||||
});
|
||||
|
||||
it('saves settings to API', async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({}) })
|
||||
.mockResolvedValueOnce({ ok: true });
|
||||
it("handles API error on load", async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error("Network error"));
|
||||
|
||||
const { result } = renderHook(() => useSettings());
|
||||
const { result } = renderHook(() => useSettings());
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settingsLoading).toBe(false);
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(result.current.settingsLoading).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
const mockEvent = { preventDefault: vi.fn() } as unknown as React.FormEvent;
|
||||
|
||||
await act(async () => {
|
||||
await result.current.saveSettings(mockEvent);
|
||||
});
|
||||
it("saves settings to API", async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({}) })
|
||||
.mockResolvedValueOnce({ ok: true });
|
||||
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
'/api/settings',
|
||||
expect.objectContaining({
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' }
|
||||
})
|
||||
);
|
||||
expect(result.current.settingsSaved).toBe(true);
|
||||
});
|
||||
const { result } = renderHook(() => useSettings());
|
||||
|
||||
it('validates email before saving', async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({})
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(result.current.settingsLoading).toBe(false);
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useSettings());
|
||||
const mockEvent = { preventDefault: vi.fn() } as unknown as React.FormEvent;
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settingsLoading).toBe(false);
|
||||
});
|
||||
await act(async () => {
|
||||
await result.current.saveSettings(mockEvent);
|
||||
});
|
||||
|
||||
// Set invalid email
|
||||
act(() => {
|
||||
result.current.setSettings(s => ({
|
||||
...s,
|
||||
emailEnabled: true,
|
||||
notificationEmail: 'invalid-email'
|
||||
}));
|
||||
});
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
"/api/settings",
|
||||
expect.objectContaining({
|
||||
method: "PUT",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
})
|
||||
);
|
||||
expect(result.current.settingsSaved).toBe(true);
|
||||
});
|
||||
|
||||
const mockEvent = { preventDefault: vi.fn() } as unknown as React.FormEvent;
|
||||
|
||||
await act(async () => {
|
||||
await result.current.saveSettings(mockEvent);
|
||||
});
|
||||
it("validates email before saving", async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({}),
|
||||
});
|
||||
|
||||
expect(result.current.testEmailResult?.success).toBe(false);
|
||||
expect(result.current.testEmailResult?.message).toContain('Invalid email');
|
||||
});
|
||||
const { result } = renderHook(() => useSettings());
|
||||
|
||||
it('tests email notification', async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({}) })
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ message: 'Email sent!' })
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(result.current.settingsLoading).toBe(false);
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useSettings());
|
||||
// Set invalid email
|
||||
act(() => {
|
||||
result.current.setSettings((s) => ({
|
||||
...s,
|
||||
emailEnabled: true,
|
||||
notificationEmail: "invalid-email",
|
||||
}));
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settingsLoading).toBe(false);
|
||||
});
|
||||
const mockEvent = { preventDefault: vi.fn() } as unknown as React.FormEvent;
|
||||
|
||||
await act(async () => {
|
||||
await result.current.testEmail();
|
||||
});
|
||||
await act(async () => {
|
||||
await result.current.saveSettings(mockEvent);
|
||||
});
|
||||
|
||||
expect(result.current.testEmailResult?.success).toBe(true);
|
||||
expect(result.current.testingEmail).toBe(false);
|
||||
});
|
||||
expect(result.current.testEmailResult?.success).toBe(false);
|
||||
expect(result.current.testEmailResult?.message).toContain("Invalid email");
|
||||
});
|
||||
|
||||
it('handles test email failure', async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({}) })
|
||||
.mockRejectedValueOnce(new Error('Network error'));
|
||||
it("tests email notification", async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({}) })
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ message: "Email sent!" }),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useSettings());
|
||||
const { result } = renderHook(() => useSettings());
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settingsLoading).toBe(false);
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(result.current.settingsLoading).toBe(false);
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.testEmail();
|
||||
});
|
||||
await act(async () => {
|
||||
await result.current.testEmail();
|
||||
});
|
||||
|
||||
expect(result.current.testEmailResult?.success).toBe(false);
|
||||
});
|
||||
expect(result.current.testEmailResult?.success).toBe(true);
|
||||
expect(result.current.testingEmail).toBe(false);
|
||||
});
|
||||
|
||||
it('tests shoutrrr notification', async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({}) })
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ message: 'Notification sent!' })
|
||||
});
|
||||
it("handles test email failure", async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({}) })
|
||||
.mockRejectedValueOnce(new Error("Network error"));
|
||||
|
||||
const { result } = renderHook(() => useSettings());
|
||||
const { result } = renderHook(() => useSettings());
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settingsLoading).toBe(false);
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(result.current.settingsLoading).toBe(false);
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.testShoutrrr();
|
||||
});
|
||||
await act(async () => {
|
||||
await result.current.testEmail();
|
||||
});
|
||||
|
||||
expect(result.current.testShoutrrrResult?.success).toBe(true);
|
||||
expect(result.current.testingShoutrrr).toBe(false);
|
||||
});
|
||||
expect(result.current.testEmailResult?.success).toBe(false);
|
||||
});
|
||||
|
||||
it('tracks unsaved changes', async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ lowStockDays: 30 })
|
||||
});
|
||||
it("tests shoutrrr notification", async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({}) })
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ message: "Notification sent!" }),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useSettings());
|
||||
const { result } = renderHook(() => useSettings());
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settingsLoading).toBe(false);
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(result.current.settingsLoading).toBe(false);
|
||||
});
|
||||
|
||||
expect(result.current.hasUnsavedChanges).toBe(false);
|
||||
await act(async () => {
|
||||
await result.current.testShoutrrr();
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.setSettings(s => ({ ...s, lowStockDays: 14 }));
|
||||
});
|
||||
expect(result.current.testShoutrrrResult?.success).toBe(true);
|
||||
expect(result.current.testingShoutrrr).toBe(false);
|
||||
});
|
||||
|
||||
expect(result.current.hasUnsavedChanges).toBe(true);
|
||||
});
|
||||
it("tracks unsaved changes", async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ lowStockDays: 30 }),
|
||||
});
|
||||
|
||||
it('loadSettings can be called manually', async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({}) })
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ lowStockDays: 14 })
|
||||
});
|
||||
const { result } = renderHook(() => useSettings());
|
||||
|
||||
const { result } = renderHook(() => useSettings());
|
||||
await waitFor(() => {
|
||||
expect(result.current.settingsLoading).toBe(false);
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settingsLoading).toBe(false);
|
||||
});
|
||||
expect(result.current.hasUnsavedChanges).toBe(false);
|
||||
|
||||
act(() => {
|
||||
result.current.loadSettings();
|
||||
});
|
||||
act(() => {
|
||||
result.current.setSettings((s) => ({ ...s, lowStockDays: 14 }));
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settings.lowStockDays).toBe(14);
|
||||
});
|
||||
});
|
||||
expect(result.current.hasUnsavedChanges).toBe(true);
|
||||
});
|
||||
|
||||
it('auto-disables email when no recipient', async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({}) })
|
||||
.mockResolvedValueOnce({ ok: true });
|
||||
it("loadSettings can be called manually", async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({}) })
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ lowStockDays: 14 }),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useSettings());
|
||||
const { result } = renderHook(() => useSettings());
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settingsLoading).toBe(false);
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(result.current.settingsLoading).toBe(false);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.setSettings(s => ({
|
||||
...s,
|
||||
emailEnabled: true,
|
||||
notificationEmail: ''
|
||||
}));
|
||||
});
|
||||
act(() => {
|
||||
result.current.loadSettings();
|
||||
});
|
||||
|
||||
const mockEvent = { preventDefault: vi.fn() } as unknown as React.FormEvent;
|
||||
|
||||
await act(async () => {
|
||||
await result.current.saveSettings(mockEvent);
|
||||
});
|
||||
await waitFor(() => {
|
||||
expect(result.current.settings.lowStockDays).toBe(14);
|
||||
});
|
||||
});
|
||||
|
||||
// emailEnabled should be false in the saved state
|
||||
expect(result.current.settings.emailEnabled).toBe(false);
|
||||
});
|
||||
it("auto-disables email when no recipient", async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>)
|
||||
.mockResolvedValueOnce({ ok: true, json: () => Promise.resolve({}) })
|
||||
.mockResolvedValueOnce({ ok: true });
|
||||
|
||||
const { result } = renderHook(() => useSettings());
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.settingsLoading).toBe(false);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.setSettings((s) => ({
|
||||
...s,
|
||||
emailEnabled: true,
|
||||
notificationEmail: "",
|
||||
}));
|
||||
});
|
||||
|
||||
const mockEvent = { preventDefault: vi.fn() } as unknown as React.FormEvent;
|
||||
|
||||
await act(async () => {
|
||||
await result.current.saveSettings(mockEvent);
|
||||
});
|
||||
|
||||
// emailEnabled should be false in the saved state
|
||||
expect(result.current.settings.emailEnabled).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,298 +1,346 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { renderHook, act, waitFor } from '@testing-library/react';
|
||||
import { useShare } from '../../hooks/useShare';
|
||||
import type { Medication } from '../../types';
|
||||
import { act, renderHook } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { useShare } from "../../hooks/useShare";
|
||||
import type { Medication } from "../../types";
|
||||
|
||||
describe('useShare', () => {
|
||||
let mockAlert: ReturnType<typeof vi.fn>;
|
||||
let mockClipboard: { writeText: ReturnType<typeof vi.fn> };
|
||||
describe("useShare", () => {
|
||||
let mockAlert: ReturnType<typeof vi.fn>;
|
||||
let mockClipboard: { writeText: ReturnType<typeof vi.fn> };
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.useFakeTimers();
|
||||
|
||||
mockAlert = vi.fn();
|
||||
global.alert = mockAlert;
|
||||
|
||||
mockClipboard = { writeText: vi.fn() };
|
||||
Object.defineProperty(navigator, 'clipboard', {
|
||||
value: mockClipboard,
|
||||
writable: true
|
||||
});
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
vi.useFakeTimers();
|
||||
|
||||
// Mock window.history
|
||||
vi.spyOn(window.history, 'pushState').mockImplementation(() => {});
|
||||
vi.spyOn(window.history, 'back').mockImplementation(() => {});
|
||||
mockAlert = vi.fn();
|
||||
global.alert = mockAlert;
|
||||
|
||||
// Mock window.location.origin
|
||||
Object.defineProperty(window, 'location', {
|
||||
value: { origin: 'http://localhost:5173' },
|
||||
writable: true
|
||||
});
|
||||
mockClipboard = { writeText: vi.fn() };
|
||||
Object.defineProperty(navigator, "clipboard", {
|
||||
value: mockClipboard,
|
||||
writable: true,
|
||||
});
|
||||
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ token: 'test-token' })
|
||||
});
|
||||
});
|
||||
// Mock window.history
|
||||
vi.spyOn(window.history, "pushState").mockImplementation(() => {});
|
||||
vi.spyOn(window.history, "back").mockImplementation(() => {});
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
// Mock window.location.origin
|
||||
Object.defineProperty(window, "location", {
|
||||
value: { origin: "http://localhost:5173" },
|
||||
writable: true,
|
||||
});
|
||||
|
||||
it('initializes with default state', () => {
|
||||
const { result } = renderHook(() => useShare());
|
||||
|
||||
expect(result.current.showShareDialog).toBe(false);
|
||||
expect(result.current.sharePeople).toEqual([]);
|
||||
expect(result.current.shareSelectedPerson).toBe('');
|
||||
expect(result.current.shareSelectedDays).toBe(30);
|
||||
expect(result.current.shareLink).toBeNull();
|
||||
});
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||
ok: true,
|
||||
json: () => Promise.resolve({ token: "test-token" }),
|
||||
});
|
||||
});
|
||||
|
||||
it('opens share dialog with people from medications', () => {
|
||||
const { result } = renderHook(() => useShare());
|
||||
|
||||
const meds: Medication[] = [
|
||||
{
|
||||
id: 1, name: 'Med1', takenBy: ['Alice', 'Bob'],
|
||||
packCount: 1, blistersPerPack: 1, pillsPerBlister: 10,
|
||||
looseTablets: 0, blisters: [], updatedAt: null
|
||||
},
|
||||
{
|
||||
id: 2, name: 'Med2', takenBy: ['Bob', 'Charlie'],
|
||||
packCount: 1, blistersPerPack: 1, pillsPerBlister: 10,
|
||||
looseTablets: 0, blisters: [], updatedAt: null
|
||||
}
|
||||
];
|
||||
afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.openShareDialog(meds);
|
||||
});
|
||||
it("initializes with default state", () => {
|
||||
const { result } = renderHook(() => useShare());
|
||||
|
||||
expect(result.current.showShareDialog).toBe(true);
|
||||
expect(result.current.sharePeople).toEqual(['Alice', 'Bob', 'Charlie']);
|
||||
expect(result.current.shareSelectedPerson).toBe('Alice');
|
||||
expect(window.history.pushState).toHaveBeenCalled();
|
||||
});
|
||||
expect(result.current.showShareDialog).toBe(false);
|
||||
expect(result.current.sharePeople).toEqual([]);
|
||||
expect(result.current.shareSelectedPerson).toBe("");
|
||||
expect(result.current.shareSelectedDays).toBe(30);
|
||||
expect(result.current.shareLink).toBeNull();
|
||||
});
|
||||
|
||||
it('resets state when opening dialog', () => {
|
||||
const { result } = renderHook(() => useShare());
|
||||
|
||||
// Set some state first
|
||||
act(() => {
|
||||
result.current.setShareLink('old-link');
|
||||
result.current.setShareCopied(true);
|
||||
});
|
||||
it("opens share dialog with people from medications", () => {
|
||||
const { result } = renderHook(() => useShare());
|
||||
|
||||
const meds: Medication[] = [
|
||||
{
|
||||
id: 1, name: 'Med1', takenBy: ['Alice'],
|
||||
packCount: 1, blistersPerPack: 1, pillsPerBlister: 10,
|
||||
looseTablets: 0, blisters: [], updatedAt: null
|
||||
}
|
||||
];
|
||||
const meds: Medication[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: "Med1",
|
||||
takenBy: ["Alice", "Bob"],
|
||||
packCount: 1,
|
||||
blistersPerPack: 1,
|
||||
pillsPerBlister: 10,
|
||||
looseTablets: 0,
|
||||
blisters: [],
|
||||
updatedAt: null,
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
name: "Med2",
|
||||
takenBy: ["Bob", "Charlie"],
|
||||
packCount: 1,
|
||||
blistersPerPack: 1,
|
||||
pillsPerBlister: 10,
|
||||
looseTablets: 0,
|
||||
blisters: [],
|
||||
updatedAt: null,
|
||||
},
|
||||
];
|
||||
|
||||
act(() => {
|
||||
result.current.openShareDialog(meds);
|
||||
});
|
||||
act(() => {
|
||||
result.current.openShareDialog(meds);
|
||||
});
|
||||
|
||||
expect(result.current.shareLink).toBeNull();
|
||||
expect(result.current.shareCopied).toBe(false);
|
||||
});
|
||||
expect(result.current.showShareDialog).toBe(true);
|
||||
expect(result.current.sharePeople).toEqual(["Alice", "Bob", "Charlie"]);
|
||||
expect(result.current.shareSelectedPerson).toBe("Alice");
|
||||
expect(window.history.pushState).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('generates share link', async () => {
|
||||
const { result } = renderHook(() => useShare());
|
||||
|
||||
const meds: Medication[] = [
|
||||
{
|
||||
id: 1, name: 'Med1', takenBy: ['Alice'],
|
||||
packCount: 1, blistersPerPack: 1, pillsPerBlister: 10,
|
||||
looseTablets: 0, blisters: [], updatedAt: null
|
||||
}
|
||||
];
|
||||
it("resets state when opening dialog", () => {
|
||||
const { result } = renderHook(() => useShare());
|
||||
|
||||
act(() => {
|
||||
result.current.openShareDialog(meds);
|
||||
});
|
||||
// Set some state first
|
||||
act(() => {
|
||||
result.current.setShareLink("old-link");
|
||||
result.current.setShareCopied(true);
|
||||
});
|
||||
|
||||
await act(async () => {
|
||||
await result.current.generateShareLink();
|
||||
});
|
||||
const meds: Medication[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: "Med1",
|
||||
takenBy: ["Alice"],
|
||||
packCount: 1,
|
||||
blistersPerPack: 1,
|
||||
pillsPerBlister: 10,
|
||||
looseTablets: 0,
|
||||
blisters: [],
|
||||
updatedAt: null,
|
||||
},
|
||||
];
|
||||
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
'/api/share',
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
body: JSON.stringify({ takenBy: 'Alice', scheduleDays: 30 })
|
||||
})
|
||||
);
|
||||
expect(result.current.shareLink).toBe('http://localhost:5173/share/test-token');
|
||||
});
|
||||
act(() => {
|
||||
result.current.openShareDialog(meds);
|
||||
});
|
||||
|
||||
it('handles share link generation error', async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: false,
|
||||
json: () => Promise.resolve({ error: 'Failed to generate' })
|
||||
});
|
||||
expect(result.current.shareLink).toBeNull();
|
||||
expect(result.current.shareCopied).toBe(false);
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useShare());
|
||||
|
||||
const meds: Medication[] = [
|
||||
{
|
||||
id: 1, name: 'Med1', takenBy: ['Alice'],
|
||||
packCount: 1, blistersPerPack: 1, pillsPerBlister: 10,
|
||||
looseTablets: 0, blisters: [], updatedAt: null
|
||||
}
|
||||
];
|
||||
it("generates share link", async () => {
|
||||
const { result } = renderHook(() => useShare());
|
||||
|
||||
act(() => {
|
||||
result.current.openShareDialog(meds);
|
||||
});
|
||||
const meds: Medication[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: "Med1",
|
||||
takenBy: ["Alice"],
|
||||
packCount: 1,
|
||||
blistersPerPack: 1,
|
||||
pillsPerBlister: 10,
|
||||
looseTablets: 0,
|
||||
blisters: [],
|
||||
updatedAt: null,
|
||||
},
|
||||
];
|
||||
|
||||
await act(async () => {
|
||||
await result.current.generateShareLink();
|
||||
});
|
||||
act(() => {
|
||||
result.current.openShareDialog(meds);
|
||||
});
|
||||
|
||||
expect(mockAlert).toHaveBeenCalled();
|
||||
expect(result.current.shareLink).toBeNull();
|
||||
});
|
||||
await act(async () => {
|
||||
await result.current.generateShareLink();
|
||||
});
|
||||
|
||||
it('handles network error on share link generation', async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error('Network error'));
|
||||
expect(fetch).toHaveBeenCalledWith(
|
||||
"/api/share",
|
||||
expect.objectContaining({
|
||||
method: "POST",
|
||||
body: JSON.stringify({ takenBy: "Alice", scheduleDays: 30 }),
|
||||
})
|
||||
);
|
||||
expect(result.current.shareLink).toBe("http://localhost:5173/share/test-token");
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useShare());
|
||||
|
||||
const meds: Medication[] = [
|
||||
{
|
||||
id: 1, name: 'Med1', takenBy: ['Alice'],
|
||||
packCount: 1, blistersPerPack: 1, pillsPerBlister: 10,
|
||||
looseTablets: 0, blisters: [], updatedAt: null
|
||||
}
|
||||
];
|
||||
it("handles share link generation error", async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
|
||||
ok: false,
|
||||
json: () => Promise.resolve({ error: "Failed to generate" }),
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.openShareDialog(meds);
|
||||
});
|
||||
const { result } = renderHook(() => useShare());
|
||||
|
||||
await act(async () => {
|
||||
await result.current.generateShareLink();
|
||||
});
|
||||
const meds: Medication[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: "Med1",
|
||||
takenBy: ["Alice"],
|
||||
packCount: 1,
|
||||
blistersPerPack: 1,
|
||||
pillsPerBlister: 10,
|
||||
looseTablets: 0,
|
||||
blisters: [],
|
||||
updatedAt: null,
|
||||
},
|
||||
];
|
||||
|
||||
expect(mockAlert).toHaveBeenCalled();
|
||||
});
|
||||
act(() => {
|
||||
result.current.openShareDialog(meds);
|
||||
});
|
||||
|
||||
it('does nothing when generateShareLink called without selected person', async () => {
|
||||
const { result } = renderHook(() => useShare());
|
||||
|
||||
// Don't open dialog, so shareSelectedPerson is empty
|
||||
await act(async () => {
|
||||
await result.current.generateShareLink();
|
||||
});
|
||||
await act(async () => {
|
||||
await result.current.generateShareLink();
|
||||
});
|
||||
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
expect(mockAlert).toHaveBeenCalled();
|
||||
expect(result.current.shareLink).toBeNull();
|
||||
});
|
||||
|
||||
it('copies share link to clipboard', async () => {
|
||||
const { result } = renderHook(() => useShare());
|
||||
|
||||
act(() => {
|
||||
result.current.setShareLink('http://localhost:5173/share/test-token');
|
||||
});
|
||||
it("handles network error on share link generation", async () => {
|
||||
(global.fetch as ReturnType<typeof vi.fn>).mockRejectedValueOnce(new Error("Network error"));
|
||||
|
||||
act(() => {
|
||||
result.current.copyShareLink();
|
||||
});
|
||||
const { result } = renderHook(() => useShare());
|
||||
|
||||
expect(mockClipboard.writeText).toHaveBeenCalledWith('http://localhost:5173/share/test-token');
|
||||
expect(result.current.shareCopied).toBe(true);
|
||||
const meds: Medication[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: "Med1",
|
||||
takenBy: ["Alice"],
|
||||
packCount: 1,
|
||||
blistersPerPack: 1,
|
||||
pillsPerBlister: 10,
|
||||
looseTablets: 0,
|
||||
blisters: [],
|
||||
updatedAt: null,
|
||||
},
|
||||
];
|
||||
|
||||
// Should reset after 2 seconds
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(2000);
|
||||
});
|
||||
|
||||
expect(result.current.shareCopied).toBe(false);
|
||||
});
|
||||
act(() => {
|
||||
result.current.openShareDialog(meds);
|
||||
});
|
||||
|
||||
it('does nothing when copyShareLink called without link', () => {
|
||||
const { result } = renderHook(() => useShare());
|
||||
|
||||
act(() => {
|
||||
result.current.copyShareLink();
|
||||
});
|
||||
await act(async () => {
|
||||
await result.current.generateShareLink();
|
||||
});
|
||||
|
||||
expect(mockClipboard.writeText).not.toHaveBeenCalled();
|
||||
});
|
||||
expect(mockAlert).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('closes share dialog with history back', () => {
|
||||
const { result } = renderHook(() => useShare());
|
||||
|
||||
const meds: Medication[] = [
|
||||
{
|
||||
id: 1, name: 'Med1', takenBy: ['Alice'],
|
||||
packCount: 1, blistersPerPack: 1, pillsPerBlister: 10,
|
||||
looseTablets: 0, blisters: [], updatedAt: null
|
||||
}
|
||||
];
|
||||
it("does nothing when generateShareLink called without selected person", async () => {
|
||||
const { result } = renderHook(() => useShare());
|
||||
|
||||
act(() => {
|
||||
result.current.openShareDialog(meds);
|
||||
});
|
||||
// Don't open dialog, so shareSelectedPerson is empty
|
||||
await act(async () => {
|
||||
await result.current.generateShareLink();
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.closeShareDialog();
|
||||
});
|
||||
expect(fetch).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
expect(window.history.back).toHaveBeenCalled();
|
||||
});
|
||||
it("copies share link to clipboard", async () => {
|
||||
const { result } = renderHook(() => useShare());
|
||||
|
||||
it('does not call history back when dialog not open', () => {
|
||||
const { result } = renderHook(() => useShare());
|
||||
|
||||
act(() => {
|
||||
result.current.closeShareDialog();
|
||||
});
|
||||
act(() => {
|
||||
result.current.setShareLink("http://localhost:5173/share/test-token");
|
||||
});
|
||||
|
||||
expect(window.history.back).not.toHaveBeenCalled();
|
||||
});
|
||||
act(() => {
|
||||
result.current.copyShareLink();
|
||||
});
|
||||
|
||||
it('resetShareDialogState clears state', () => {
|
||||
const { result } = renderHook(() => useShare());
|
||||
|
||||
const meds: Medication[] = [
|
||||
{
|
||||
id: 1, name: 'Med1', takenBy: ['Alice'],
|
||||
packCount: 1, blistersPerPack: 1, pillsPerBlister: 10,
|
||||
looseTablets: 0, blisters: [], updatedAt: null
|
||||
}
|
||||
];
|
||||
expect(mockClipboard.writeText).toHaveBeenCalledWith("http://localhost:5173/share/test-token");
|
||||
expect(result.current.shareCopied).toBe(true);
|
||||
|
||||
act(() => {
|
||||
result.current.openShareDialog(meds);
|
||||
result.current.setShareLink('some-link');
|
||||
result.current.setShareCopied(true);
|
||||
});
|
||||
// Should reset after 2 seconds
|
||||
act(() => {
|
||||
vi.advanceTimersByTime(2000);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.resetShareDialogState();
|
||||
});
|
||||
expect(result.current.shareCopied).toBe(false);
|
||||
});
|
||||
|
||||
expect(result.current.showShareDialog).toBe(false);
|
||||
expect(result.current.shareLink).toBeNull();
|
||||
expect(result.current.shareCopied).toBe(false);
|
||||
});
|
||||
it("does nothing when copyShareLink called without link", () => {
|
||||
const { result } = renderHook(() => useShare());
|
||||
|
||||
it('allows changing selected person and days', () => {
|
||||
const { result } = renderHook(() => useShare());
|
||||
|
||||
act(() => {
|
||||
result.current.setShareSelectedPerson('Bob');
|
||||
result.current.setShareSelectedDays(90);
|
||||
});
|
||||
act(() => {
|
||||
result.current.copyShareLink();
|
||||
});
|
||||
|
||||
expect(result.current.shareSelectedPerson).toBe('Bob');
|
||||
expect(result.current.shareSelectedDays).toBe(90);
|
||||
});
|
||||
expect(mockClipboard.writeText).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("closes share dialog with history back", () => {
|
||||
const { result } = renderHook(() => useShare());
|
||||
|
||||
const meds: Medication[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: "Med1",
|
||||
takenBy: ["Alice"],
|
||||
packCount: 1,
|
||||
blistersPerPack: 1,
|
||||
pillsPerBlister: 10,
|
||||
looseTablets: 0,
|
||||
blisters: [],
|
||||
updatedAt: null,
|
||||
},
|
||||
];
|
||||
|
||||
act(() => {
|
||||
result.current.openShareDialog(meds);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.closeShareDialog();
|
||||
});
|
||||
|
||||
expect(window.history.back).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not call history back when dialog not open", () => {
|
||||
const { result } = renderHook(() => useShare());
|
||||
|
||||
act(() => {
|
||||
result.current.closeShareDialog();
|
||||
});
|
||||
|
||||
expect(window.history.back).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("resetShareDialogState clears state", () => {
|
||||
const { result } = renderHook(() => useShare());
|
||||
|
||||
const meds: Medication[] = [
|
||||
{
|
||||
id: 1,
|
||||
name: "Med1",
|
||||
takenBy: ["Alice"],
|
||||
packCount: 1,
|
||||
blistersPerPack: 1,
|
||||
pillsPerBlister: 10,
|
||||
looseTablets: 0,
|
||||
blisters: [],
|
||||
updatedAt: null,
|
||||
},
|
||||
];
|
||||
|
||||
act(() => {
|
||||
result.current.openShareDialog(meds);
|
||||
result.current.setShareLink("some-link");
|
||||
result.current.setShareCopied(true);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.resetShareDialogState();
|
||||
});
|
||||
|
||||
expect(result.current.showShareDialog).toBe(false);
|
||||
expect(result.current.shareLink).toBeNull();
|
||||
expect(result.current.shareCopied).toBe(false);
|
||||
});
|
||||
|
||||
it("allows changing selected person and days", () => {
|
||||
const { result } = renderHook(() => useShare());
|
||||
|
||||
act(() => {
|
||||
result.current.setShareSelectedPerson("Bob");
|
||||
result.current.setShareSelectedDays(90);
|
||||
});
|
||||
|
||||
expect(result.current.shareSelectedPerson).toBe("Bob");
|
||||
expect(result.current.shareSelectedDays).toBe(90);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,74 +1,74 @@
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { useTheme } from '../../hooks/useTheme';
|
||||
import { act, renderHook } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { useTheme } from "../../hooks/useTheme";
|
||||
|
||||
describe('useTheme', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
(window.localStorage.getItem as ReturnType<typeof vi.fn>).mockReturnValue(null);
|
||||
// Reset mock to default behavior
|
||||
(window.localStorage.setItem as ReturnType<typeof vi.fn>).mockImplementation(() => {});
|
||||
});
|
||||
describe("useTheme", () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
(window.localStorage.getItem as ReturnType<typeof vi.fn>).mockReturnValue(null);
|
||||
// Reset mock to default behavior
|
||||
(window.localStorage.setItem as ReturnType<typeof vi.fn>).mockImplementation(() => {});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
afterEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('returns dark as default theme', () => {
|
||||
const { result } = renderHook(() => useTheme());
|
||||
expect(result.current.theme).toBe('dark');
|
||||
});
|
||||
it("returns dark as default theme", () => {
|
||||
const { result } = renderHook(() => useTheme());
|
||||
expect(result.current.theme).toBe("dark");
|
||||
});
|
||||
|
||||
it('reads theme from localStorage', () => {
|
||||
(window.localStorage.getItem as ReturnType<typeof vi.fn>).mockReturnValue('light');
|
||||
const { result } = renderHook(() => useTheme());
|
||||
expect(result.current.theme).toBe('light');
|
||||
});
|
||||
it("reads theme from localStorage", () => {
|
||||
(window.localStorage.getItem as ReturnType<typeof vi.fn>).mockReturnValue("light");
|
||||
const { result } = renderHook(() => useTheme());
|
||||
expect(result.current.theme).toBe("light");
|
||||
});
|
||||
|
||||
it('toggles theme from dark to light', () => {
|
||||
const { result } = renderHook(() => useTheme());
|
||||
|
||||
expect(result.current.theme).toBe('dark');
|
||||
|
||||
act(() => {
|
||||
result.current.toggleTheme();
|
||||
});
|
||||
|
||||
expect(result.current.theme).toBe('light');
|
||||
});
|
||||
it("toggles theme from dark to light", () => {
|
||||
const { result } = renderHook(() => useTheme());
|
||||
|
||||
it('toggles theme from light to dark', () => {
|
||||
(window.localStorage.getItem as ReturnType<typeof vi.fn>).mockReturnValue('light');
|
||||
const { result } = renderHook(() => useTheme());
|
||||
|
||||
expect(result.current.theme).toBe('light');
|
||||
|
||||
act(() => {
|
||||
result.current.toggleTheme();
|
||||
});
|
||||
|
||||
expect(result.current.theme).toBe('dark');
|
||||
});
|
||||
expect(result.current.theme).toBe("dark");
|
||||
|
||||
it('saves theme to localStorage on change', () => {
|
||||
const { result } = renderHook(() => useTheme());
|
||||
|
||||
act(() => {
|
||||
result.current.toggleTheme();
|
||||
});
|
||||
|
||||
expect(window.localStorage.setItem).toHaveBeenCalledWith('theme', 'light');
|
||||
});
|
||||
act(() => {
|
||||
result.current.toggleTheme();
|
||||
});
|
||||
|
||||
it('sets data-theme attribute on document', () => {
|
||||
const { result } = renderHook(() => useTheme());
|
||||
|
||||
expect(document.documentElement.getAttribute('data-theme')).toBe('dark');
|
||||
|
||||
act(() => {
|
||||
result.current.toggleTheme();
|
||||
});
|
||||
|
||||
expect(document.documentElement.getAttribute('data-theme')).toBe('light');
|
||||
});
|
||||
expect(result.current.theme).toBe("light");
|
||||
});
|
||||
|
||||
it("toggles theme from light to dark", () => {
|
||||
(window.localStorage.getItem as ReturnType<typeof vi.fn>).mockReturnValue("light");
|
||||
const { result } = renderHook(() => useTheme());
|
||||
|
||||
expect(result.current.theme).toBe("light");
|
||||
|
||||
act(() => {
|
||||
result.current.toggleTheme();
|
||||
});
|
||||
|
||||
expect(result.current.theme).toBe("dark");
|
||||
});
|
||||
|
||||
it("saves theme to localStorage on change", () => {
|
||||
const { result } = renderHook(() => useTheme());
|
||||
|
||||
act(() => {
|
||||
result.current.toggleTheme();
|
||||
});
|
||||
|
||||
expect(window.localStorage.setItem).toHaveBeenCalledWith("theme", "light");
|
||||
});
|
||||
|
||||
it("sets data-theme attribute on document", () => {
|
||||
const { result } = renderHook(() => useTheme());
|
||||
|
||||
expect(document.documentElement.getAttribute("data-theme")).toBe("dark");
|
||||
|
||||
act(() => {
|
||||
result.current.toggleTheme();
|
||||
});
|
||||
|
||||
expect(document.documentElement.getAttribute("data-theme")).toBe("light");
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user