fixed tests and Code edit and delete Name in TatortList
This commit is contained in:
@@ -8,35 +8,33 @@
|
|||||||
interface ListItem {
|
interface ListItem {
|
||||||
name: string;
|
name: string;
|
||||||
token?: string;
|
token?: string;
|
||||||
// add other properties as needed
|
|
||||||
}
|
}
|
||||||
let { list, currentName, onSave = () => {}, onDelete = () => {} } = $props();
|
|
||||||
|
|
||||||
let localName = $state(currentName);
|
export let list: ListItem[] = [];
|
||||||
let isEditing = $state(false);
|
export let currentName: string = '';
|
||||||
|
export let onSave: (n: string, o: string) => unknown = () => {};
|
||||||
|
export let onDelete: (n: string) => unknown = () => {};
|
||||||
|
|
||||||
let error = $derived(() => validateName(localName));
|
// lokaler State
|
||||||
|
let localName = currentName;
|
||||||
|
let isEditing = false;
|
||||||
|
let inputRef: HTMLInputElement | null = null;
|
||||||
|
|
||||||
let inputRef = $state<HTMLInputElement | null>(null);
|
$: error = validateName(localName);
|
||||||
|
|
||||||
function validateName(name: string | undefined | null) {
|
|
||||||
if (!name) return 'Name darf nicht leer sein.';
|
|
||||||
const trimmed = name.trim();
|
|
||||||
|
|
||||||
|
function validateName(name: string): string {
|
||||||
|
const trimmed = name?.trim() ?? '';
|
||||||
if (!trimmed) return 'Name darf nicht leer sein.';
|
if (!trimmed) return 'Name darf nicht leer sein.';
|
||||||
|
if (list.some((item) => item.name === trimmed && item.name !== currentName)) {
|
||||||
const duplicate = list.some(
|
return 'Name existiert bereits.';
|
||||||
(item: ListItem) => item.name === trimmed && item.name !== currentName
|
}
|
||||||
);
|
|
||||||
|
|
||||||
if (duplicate) return 'Name existiert bereits.';
|
|
||||||
|
|
||||||
return '';
|
return '';
|
||||||
}
|
}
|
||||||
|
|
||||||
function startEdit() {
|
async function startEdit() {
|
||||||
isEditing = true;
|
isEditing = true;
|
||||||
tick().then(() => inputRef?.focus());
|
await tick();
|
||||||
|
inputRef?.focus();
|
||||||
}
|
}
|
||||||
|
|
||||||
function cancelEdit() {
|
function cancelEdit() {
|
||||||
@@ -45,7 +43,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
function commitEdit() {
|
function commitEdit() {
|
||||||
if (!error() && localName != currentName) onSave(localName, currentName);
|
if (!error && localName != currentName) onSave(localName, currentName);
|
||||||
|
|
||||||
isEditing = false;
|
isEditing = false;
|
||||||
}
|
}
|
||||||
@@ -54,6 +52,10 @@
|
|||||||
if (event.key === 'Enter') commitEdit();
|
if (event.key === 'Enter') commitEdit();
|
||||||
if (event.key === 'Escape') cancelEdit();
|
if (event.key === 'Escape') cancelEdit();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function handleDeleteClick() {
|
||||||
|
onDelete(currentName);
|
||||||
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div data-testid="test-nameItemEditor">
|
<div data-testid="test-nameItemEditor">
|
||||||
@@ -64,14 +66,18 @@
|
|||||||
bind:value={localName}
|
bind:value={localName}
|
||||||
onkeydown={handleKeydown}
|
onkeydown={handleKeydown}
|
||||||
/>
|
/>
|
||||||
<button data-testid="commit-button" onclick={commitEdit}><Check /></button>
|
<button
|
||||||
|
data-testid="commit-button"
|
||||||
|
disabled={!!error || localName === currentName}
|
||||||
|
onclick={commitEdit}><Check /></button
|
||||||
|
>
|
||||||
<button data-testid="cancel-button" onclick={cancelEdit}><X /></button>
|
<button data-testid="cancel-button" onclick={cancelEdit}><X /></button>
|
||||||
{:else}
|
{:else}
|
||||||
<span>{localName}</span>
|
<span>{localName}</span>
|
||||||
<button data-testid="edit-button" onclick={startEdit}><Edit /></button>
|
<button data-testid="edit-button" onclick={startEdit}><Edit /></button>
|
||||||
<button data-testid="delete-button" onclick={() => onDelete(currentName)}><Trash /></button>
|
<button data-testid="delete-button" onclick={handleDeleteClick}><Trash /></button>
|
||||||
{/if}
|
{/if}
|
||||||
{#if error()}
|
{#if error}
|
||||||
<p class="text-red-500">{error()}</p>
|
<p class="text-red-500">{error}</p>
|
||||||
{/if}
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -26,11 +26,12 @@
|
|||||||
// add other properties as needed
|
// add other properties as needed
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 2) Lokaler, reaktiver State mit $state
|
||||||
|
let crimesList = $state<ListItem[]>(data.crimesList);
|
||||||
let vorgangName: string = data.vorgang.vorgangName;
|
let vorgangName: string = data.vorgang.vorgangName;
|
||||||
let crimesList: ListItem[] = $state(data.crimesList);
|
|
||||||
const vorgangPIN: string = data.vorgang.vorgangPIN;
|
const vorgangPIN: string = data.vorgang.vorgangPIN;
|
||||||
let vorgangToken: string = data.vorgang.vorgangToken;
|
let vorgangToken: string = data.vorgang.vorgangToken;
|
||||||
let isEmptyList = $derived(crimesList && crimesList.length === 0);
|
let isEmptyList = $derived(crimesList.length === 0);
|
||||||
|
|
||||||
//Variablen für Modal
|
//Variablen für Modal
|
||||||
let open = $state(false);
|
let open = $state(false);
|
||||||
@@ -38,11 +39,12 @@
|
|||||||
let isError = $state(false);
|
let isError = $state(false);
|
||||||
|
|
||||||
//Variable um nur admin UI anzuzeigen
|
//Variable um nur admin UI anzuzeigen
|
||||||
let admin = data?.user?.admin;
|
let admin = $state(data?.user?.admin);
|
||||||
|
|
||||||
async function handleSave(newName: string, oldName: string) {
|
async function handleSave(newName: string, oldName: string) {
|
||||||
open = true;
|
open = true;
|
||||||
inProgress = true;
|
inProgress = true;
|
||||||
|
isError = false;
|
||||||
console.log('debug handleSave', newName, oldName);
|
console.log('debug handleSave', newName, oldName);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
@@ -54,20 +56,15 @@
|
|||||||
body: JSON.stringify({ vorgangToken, oldName, newName })
|
body: JSON.stringify({ vorgangToken, oldName, newName })
|
||||||
});
|
});
|
||||||
|
|
||||||
if (res.ok) {
|
if (!res.ok) {
|
||||||
inProgress = false;
|
|
||||||
invalidateAll();
|
|
||||||
data.crimesList = newName;
|
|
||||||
open = false;
|
|
||||||
} else {
|
|
||||||
inProgress = false;
|
|
||||||
isError = true;
|
|
||||||
throw new Error('Fehler beim Speichern');
|
throw new Error('Fehler beim Speichern');
|
||||||
}
|
}
|
||||||
|
await invalidateAll();
|
||||||
|
open = false;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
console.error('⚠️ Netzwerkfehler beim Speichern', err);
|
||||||
isError = true;
|
isError = true;
|
||||||
inProgress = false;
|
} finally {
|
||||||
console.error('⚠️ Netzwerkfehler:', err);
|
|
||||||
inProgress = false;
|
inProgress = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -75,32 +72,31 @@
|
|||||||
async function handleDelete(tatort: string) {
|
async function handleDelete(tatort: string) {
|
||||||
open = true;
|
open = true;
|
||||||
inProgress = true;
|
inProgress = true;
|
||||||
let url = new URL(data.url);
|
isError = false;
|
||||||
url.pathname += `/${tatort}`;
|
let path = new URL(data.url).pathname;
|
||||||
|
path += `/${tatort}`;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`/api${url.pathname}`, {
|
const res = await fetch(`/api${path}`, {
|
||||||
method: 'DELETE',
|
method: 'DELETE',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json'
|
'Content-Type': 'application/json'
|
||||||
},
|
},
|
||||||
body: JSON.stringify({ vorgangToken, tatort })
|
body: JSON.stringify({ vorgangToken, tatort })
|
||||||
})
|
|
||||||
.then(() => {
|
|
||||||
inProgress = false;
|
|
||||||
console.log('🗑️ Erfolgreich gelöscht:', url.pathname);
|
|
||||||
invalidateAll();
|
|
||||||
crimesList = data.crimesList;
|
|
||||||
})
|
|
||||||
.catch((err) => {
|
|
||||||
isError = true;
|
|
||||||
inProgress = false;
|
|
||||||
console.error('ERROR', err);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error('Fehler beim Löschen');
|
||||||
|
}
|
||||||
|
crimesList = crimesList.filter((i) => i.name !== tatort);
|
||||||
|
await invalidateAll();
|
||||||
|
console.log('🗑️ Erfolgreich gelöscht:', path);
|
||||||
|
open = false;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
|
console.error('⚠️ Netzwerkfehler beim Speichern', err);
|
||||||
isError = true;
|
isError = true;
|
||||||
|
} finally {
|
||||||
inProgress = false;
|
inProgress = false;
|
||||||
console.error('⚠️ Netzwerkfehler beim Löschen:', err);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -129,7 +125,7 @@ Mit freundlichen Grüßen,
|
|||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
{#if data.vorgang && data.crimesList}
|
{#if data.vorgang && crimesList}
|
||||||
<div class="-z-10 bg-white">
|
<div class="-z-10 bg-white">
|
||||||
<div class="flex flex-col items-center justify-center w-full">
|
<div class="flex flex-col items-center justify-center w-full">
|
||||||
<h1 class="text-xl">Vorgang {vorgangName}</h1>
|
<h1 class="text-xl">Vorgang {vorgangName}</h1>
|
||||||
@@ -146,7 +142,7 @@ Mit freundlichen Grüßen,
|
|||||||
{#if isEmptyList}
|
{#if isEmptyList}
|
||||||
<EmptyList></EmptyList>
|
<EmptyList></EmptyList>
|
||||||
{:else}
|
{:else}
|
||||||
{#each data.crimesList as item}
|
{#each crimesList as item (item.name)}
|
||||||
<li data-testid="test-list-item">
|
<li data-testid="test-list-item">
|
||||||
<div class=" flex gap-x-4">
|
<div class=" flex gap-x-4">
|
||||||
<a
|
<a
|
||||||
@@ -161,7 +157,7 @@ Mit freundlichen Grüßen,
|
|||||||
<div class="min-w-0 flex-auto">
|
<div class="min-w-0 flex-auto">
|
||||||
{#if admin}
|
{#if admin}
|
||||||
<NameItemEditor
|
<NameItemEditor
|
||||||
list={data.crimesList}
|
list={crimesList}
|
||||||
currentName={item.name}
|
currentName={item.name}
|
||||||
onSave={handleSave}
|
onSave={handleSave}
|
||||||
onDelete={handleDelete}
|
onDelete={handleDelete}
|
||||||
|
|||||||
@@ -1,94 +1,103 @@
|
|||||||
import { fireEvent, getByTestId, queryAllByTestId, render, screen, within } from '@testing-library/svelte';
|
// @vitest-environment jsdom
|
||||||
import { describe, expect, it, test, vi } from "vitest";
|
import { render, fireEvent, screen, within } from '@testing-library/svelte';
|
||||||
import TatortListPage from "../src/routes/(token-based)/list/[vorgang]/+page.svelte";
|
import { describe, it, expect, vi, test } from 'vitest';
|
||||||
|
import * as nav from '$app/navigation';
|
||||||
|
import TatortListPage from '../src/routes/(token-based)/list/[vorgang]/+page.svelte';
|
||||||
import { baseData } from './fixtures';
|
import { baseData } from './fixtures';
|
||||||
import { invalidateAll } from '$app/navigation';
|
import { tick } from 'svelte';
|
||||||
|
|
||||||
|
|
||||||
// Mock für invalidateAll
|
// Mock für invalidateAll
|
||||||
vi.mock('$app/navigation', () => ({
|
vi.spyOn(nav, 'invalidateAll').mockResolvedValue();
|
||||||
invalidateAll: vi.fn()
|
global.fetch = vi.fn().mockResolvedValue({ ok: true });
|
||||||
}));
|
|
||||||
|
|
||||||
|
|
||||||
describe('Seite: Vorgangsansicht', () => {
|
describe('Seite: Vorgangsansicht', () => {
|
||||||
test.todo('Share Link disabled wenn Liste leer');
|
test.todo('Share Link disabled wenn Liste leer');
|
||||||
describe('Szenario: Admin + Liste gefüllt', () => {
|
describe('Szenario: Admin + Liste gefüllt - Funktionalität', () => {
|
||||||
test.todo('Share Link Link generierung richtig');
|
test.todo('Share Link Link generierung richtig');
|
||||||
|
|
||||||
it('ändert den Namen nach Speichern', async () => {
|
|
||||||
const testData = structuredClone(baseData);
|
|
||||||
const oldName = testData.crimesList[0].name;
|
|
||||||
const newName = 'Fall-B';
|
|
||||||
const list = testData.crimesList
|
|
||||||
const vorgangToken = testData.vorgang.vorgangToken
|
|
||||||
// Minimaler fetch-Mock
|
|
||||||
global.fetch = vi.fn().mockResolvedValue({ ok: true }) as typeof fetch;
|
|
||||||
|
|
||||||
const { getAllByTestId } = render(TatortListPage, { props: { data: testData } });
|
it('führt PUT-Request aus und aktualisiert UI nach onSave', async () => {
|
||||||
|
const data = structuredClone(baseData);
|
||||||
|
const oldName = data.crimesList[0].name;
|
||||||
|
const newName = 'Fall-C';
|
||||||
|
|
||||||
const firstItem = getAllByTestId('test-list-item')[0];
|
render(TatortListPage, { props: { data } });
|
||||||
const editButton = within(firstItem).getByTestId('edit-button');
|
const listItem = screen.getAllByTestId('test-list-item')[0];
|
||||||
await fireEvent.click(editButton);
|
// teste ob alter Name angezeigt:
|
||||||
|
expect(listItem).toHaveTextContent(oldName);
|
||||||
|
|
||||||
const input = within(firstItem).getByTestId('test-input');
|
// Editmodus
|
||||||
expect(input).toHaveValue(oldName)
|
await fireEvent.click(within(listItem).getByTestId('edit-button'));
|
||||||
|
const input = within(listItem).getByTestId('test-input');
|
||||||
await fireEvent.input(input, { target: { value: newName } });
|
await fireEvent.input(input, { target: { value: newName } });
|
||||||
|
|
||||||
const commitButton = within(firstItem).getByTestId('commit-button');
|
// Commit
|
||||||
await fireEvent.click(commitButton);
|
await fireEvent.click(within(listItem).getByTestId('commit-button'));
|
||||||
|
await Promise.resolve(); // wartet reaktive Updates ab
|
||||||
|
|
||||||
// const fetchMock = global.fetch as ReturnType<typeof vi.fn>;
|
// FETCH-CHECK
|
||||||
// console.log('Fetch calls:', fetchMock.mock.calls);
|
expect(global.fetch).toHaveBeenCalledWith(
|
||||||
|
`/api/list/${data.vorgang.vorgangToken}/${oldName}`,
|
||||||
|
expect.objectContaining({
|
||||||
|
method: 'PUT',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
vorgangToken: data.vorgang.vorgangToken,
|
||||||
|
oldName,
|
||||||
|
newName
|
||||||
|
})
|
||||||
|
})
|
||||||
|
);
|
||||||
|
|
||||||
// // Erwartung: fetch wurde aufgerufen
|
// INVALIDATE-CHECK
|
||||||
// expect(global.fetch).toHaveBeenCalledWith(
|
expect(nav.invalidateAll).toHaveBeenCalled();
|
||||||
// expect.stringContaining(`/api/list/${vorgangToken}/${oldName}`),
|
|
||||||
// expect.objectContaining({
|
|
||||||
// method: 'PUT',
|
|
||||||
// headers: { 'Content-Type': 'application/json' },
|
|
||||||
// body: JSON.stringify({vorgangToken, oldName, newName})
|
|
||||||
// })
|
|
||||||
// );
|
|
||||||
|
|
||||||
// expect(invalidateAll).toHaveBeenCalled();
|
// UI-UPDATE
|
||||||
// Erwartung: neuer Name ist sofort im DOM sichtbar
|
expect(within(listItem).getByText(newName)).toBeInTheDocument();
|
||||||
// expect(within(firstItem).getByRole('textbox')).toHaveValue(newName);
|
|
||||||
// const editedLink = within(firstItem).getByRole('link');
|
|
||||||
// const editedExpectedHref = `/view/${vorgangToken}/${newName}?pin=${testData.vorgang.vorgangPIN}`;
|
|
||||||
|
|
||||||
// expect(editedLink).toBeInTheDocument();
|
|
||||||
// expect(editedLink).toHaveAttribute('href', editedExpectedHref);
|
|
||||||
// expect(editedLink).toHaveAttribute('title', newName);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
// it('entfernt das Listenelement nach Löschen', async () => {
|
it('führt DELETE-Request aus und entfernt Element aus UI', async () => {
|
||||||
// const testData = structuredClone(baseData);
|
const testData = structuredClone(baseData);
|
||||||
// testData.url = new URL('https://example.com/vorgang-1'); // Fix für Invalid URL
|
const oldName = testData.crimesList[0].name;
|
||||||
// const toDelete = testData.crimesList[0];
|
|
||||||
|
|
||||||
// global.fetch = vi.fn().mockResolvedValue({ ok: true });
|
// Rendern und initiale Liste prüfen
|
||||||
|
render(TatortListPage, { props: { data: testData } });
|
||||||
|
const initialItems = screen.getAllByTestId('test-list-item');
|
||||||
|
expect(initialItems).toHaveLength(testData.crimesList.length);
|
||||||
|
|
||||||
// render(TatortListPage, { props: { data: testData } });
|
const listItem = screen.getAllByTestId('test-list-item')[0];
|
||||||
// const deletedFirstItem = screen.getAllByTestId('test-list-item')[0];
|
// teste ob alter Name angezeigt:
|
||||||
// const deletedLink = within(deletedFirstItem).getByRole('link');
|
expect(listItem).toHaveTextContent(oldName);
|
||||||
// const deletedExpectedHref = `/view/${testData.vorgang.vorgangToken}/${toDelete.name}?pin=${testData.vorgang.vorgangPIN}`;
|
// Delete-Button klicken
|
||||||
|
const del = within(listItem).getByTestId('delete-button');
|
||||||
|
expect(del).toBeInTheDocument()
|
||||||
|
await fireEvent.click(within(listItem).getByTestId('delete-button'));
|
||||||
|
// auf reaktive Updates warten
|
||||||
|
await tick();
|
||||||
|
|
||||||
// expect(deletedLink).toBeInTheDocument();
|
// FETCH-CHECK: URL & Payload
|
||||||
// expect(deletedLink).toHaveAttribute('href', deletedExpectedHref);
|
// entspricht: new URL(data.url).pathname + '/' + oldName
|
||||||
// expect(deletedLink).toHaveAttribute('title', toDelete.name);
|
const expectedPath = new URL(testData.url).pathname;
|
||||||
// await fireEvent.click(within(deletedFirstItem).getByTestId('delete-button'));
|
expect(global.fetch).toHaveBeenCalledWith(
|
||||||
|
`/api${expectedPath}/${oldName}`,
|
||||||
|
expect.objectContaining({
|
||||||
|
method: 'DELETE',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({
|
||||||
|
vorgangToken: testData.vorgang.vorgangToken,
|
||||||
|
tatort: oldName
|
||||||
|
})
|
||||||
|
})
|
||||||
|
);
|
||||||
|
// INVALIDATE-CHECK
|
||||||
|
expect(nav.invalidateAll).toHaveBeenCalled();
|
||||||
|
|
||||||
// // Erwartung: fetch wurde aufgerufen
|
// UI-UPDATE: Element entfernt
|
||||||
// expect(global.fetch).toHaveBeenCalledWith(
|
const updatedItems = screen.queryAllByTestId('test-list-item');
|
||||||
// expect.stringContaining(`/api/vorgang-1/${toDelete.name}`),
|
expect(updatedItems).toHaveLength(testData.crimesList.length - 1);
|
||||||
// expect.any(Object)
|
expect(screen.queryByText(oldName)).toBeNull();
|
||||||
// );
|
|
||||||
|
|
||||||
// // Erwartung: Element ist nicht mehr im DOM
|
});
|
||||||
// expect(within(deletedFirstItem).getByRole('textbox')).toHaveValue(toDelete.name);
|
|
||||||
// });
|
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -6,7 +6,7 @@ id: "admin",
|
|||||||
}
|
}
|
||||||
const testCrimesList = [
|
const testCrimesList = [
|
||||||
{
|
{
|
||||||
name: 'modell-A',
|
name: 'Fall-A',
|
||||||
lastModified: '2025-08-28T09:44:12.453Z',
|
lastModified: '2025-08-28T09:44:12.453Z',
|
||||||
etag: '558f35716f6af953f9bb5d75f6d77e6a',
|
etag: '558f35716f6af953f9bb5d75f6d77e6a',
|
||||||
size: 8947140,
|
size: 8947140,
|
||||||
@@ -14,7 +14,7 @@ const testCrimesList = [
|
|||||||
show_button: true
|
show_button: true
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
name: 'Fall-A',
|
name: 'Fall-B',
|
||||||
lastModified: '2025-08-28T10:37:20.142Z',
|
lastModified: '2025-08-28T10:37:20.142Z',
|
||||||
etag: '43e3989c32c4682bee407baaf83b6fa0',
|
etag: '43e3989c32c4682bee407baaf83b6fa0',
|
||||||
size: 35788560,
|
size: 35788560,
|
||||||
@@ -42,6 +42,6 @@ export const baseData = {
|
|||||||
vorgang: testVorgangsList[0],
|
vorgang: testVorgangsList[0],
|
||||||
vorgangList: testVorgangsList,
|
vorgangList: testVorgangsList,
|
||||||
crimesList: testCrimesList,
|
crimesList: testCrimesList,
|
||||||
url: new URL(`https://example.com/${testVorgangsList[0].vorgangToken}`),
|
url: `https://example.com/${testVorgangsList[0].vorgangToken}`,
|
||||||
crimeNames: [ "modell-A", "Fall-A" ],
|
crimeNames: [ "modell-A", "Fall-A" ],
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user