import {test} from 'node:test';
import assert from 'node:assert/strict';
import {loadPage} from './learnrun.js';
const add = (page, text) => {
page.document.querySelector('#add').elements.entry.value = text;
page.document.querySelector('#add').requestSubmit();
};
const shown = (page) => [...page.document.querySelectorAll('#list li')].map((li) => li.textContent);
const field = (page) => page.document.querySelector('#add').elements.entry;
test('Submitting adds the text to the list', async () => {
const page = await loadPage();
add(page, 'milk');
assert.deepEqual(shown(page), ['milk'], 'the list shows ' + JSON.stringify(shown(page)));
});
test('The text is trimmed and the field is cleared', async () => {
const page = await loadPage();
add(page, ' tea ');
assert.deepEqual(shown(page), ['tea'], 'the list shows ' + JSON.stringify(shown(page)));
assert.equal(field(page).value, '', 'after adding, the field holds ' + JSON.stringify(field(page).value));
});
test('A blank entry adds nothing', async () => {
const page = await loadPage();
add(page, ' ');
assert.deepEqual(shown(page), [], 'the list shows ' + JSON.stringify(shown(page)));
});
test('The submit is cancelled with preventDefault()', async () => {
const page = await loadPage();
const form = page.document.querySelector('#add');
let cancelled = false;
form.addEventListener('submit', (event) => {
cancelled = event.defaultPrevented;
});
add(page, 'milk');
assert.equal(cancelled, true, 'the submit event was not cancelled');
});
test('Escape clears the field', async () => {
const page = await loadPage();
field(page).value = 'oops';
field(page).dispatchEvent(new page.window.KeyboardEvent('keydown', { key: 'Escape', bubbles: true }));
assert.equal(field(page).value, '', 'after Escape the field holds ' + JSON.stringify(field(page).value));
});
test('Other keys leave the field alone', async () => {
const page = await loadPage();
field(page).value = 'tea';
field(page).dispatchEvent(new page.window.KeyboardEvent('keydown', { key: 'a', bubbles: true }));
assert.equal(field(page).value, 'tea', 'after the key a the field holds ' + JSON.stringify(field(page).value));
});