// test/notes.test.mjs: the notes API over a store double, with no database. import assert from 'node:assert/strict'; import test from 'node:test'; import { createNotesApi } from '../lib/notes.js'; function double() { const notes = []; return { async addNote(title) { const note = { id: String(notes.length + 1), title }; notes.push(note); return note; }, async listNotes() { return [...notes]; }, }; } const ADDRESS = 'http://localhost/api/notes'; const post = (body) => new Request(ADDRESS, { method: 'POST', headers: { 'content-type': 'application/json' }, body }); test('POST adds a note and GET lists it', async () => { const api = createNotesApi(double()); const added = await api(post(JSON.stringify({ title: ' first ' }))); assert.equal(added.status, 201); assert.deepEqual(await added.json(), { id: '1', title: 'first' }); const listed = await api(new Request(ADDRESS)); assert.equal(listed.status, 200); assert.deepEqual(await listed.json(), { notes: [{ id: '1', title: 'first' }] }); }); test('a POST with no title, or with no JSON, returns 400 invalid_request and adds nothing', async () => { const store = double(); const api = createNotesApi(store); for (const body of [JSON.stringify({ title: ' ' }), JSON.stringify({}), 'not json']) { const refused = await api(post(body)); assert.equal(refused.status, 400); assert.equal((await refused.json()).error, 'invalid_request'); } assert.deepEqual(await store.listNotes(), []); }); test('a POST with a title longer than 200 characters returns 400 invalid_request and adds nothing', async () => { const store = double(); const api = createNotesApi(store); const refused = await api(post(JSON.stringify({ title: 'a'.repeat(201) }))); assert.equal(refused.status, 400); assert.equal((await refused.json()).error, 'invalid_request'); assert.deepEqual(await store.listNotes(), []); const added = await api(post(JSON.stringify({ title: 'a'.repeat(200) }))); assert.equal(added.status, 201); }); test('another method returns 405 method_not_allowed', async () => { const refused = await createNotesApi(double())(new Request(ADDRESS, { method: 'DELETE' })); assert.equal(refused.status, 405); assert.equal(refused.headers.get('allow'), 'GET, POST'); assert.equal((await refused.json()).error, 'method_not_allowed'); });