Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions sample-app/src/app.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,58 @@ describe('Task API', () => {
expect(list.body).toHaveLength(1);
});

it('trims surrounding whitespace from the title', async () => {
const app = createApp();
const created = await request(app).post('/tasks').send({ title: ' Padded title ' });

expect(created.status).toBe(201);
expect(created.body.title).toBe('Padded title');
});

it('rejects a missing title with 400 and creates no task', async () => {
const app = createApp();

const res = await request(app).post('/tasks').send({});
expect(res.status).toBe(400);
expect(res.body).toEqual({
error: 'title is required and must be a non-empty string',
});

const list = await request(app).get('/tasks');
expect(list.body).toHaveLength(0);
});

it('rejects an empty or whitespace-only title with 400 and creates no task', async () => {
const app = createApp();

const empty = await request(app).post('/tasks').send({ title: '' });
expect(empty.status).toBe(400);
expect(empty.body.error).toContain('title');

const whitespace = await request(app).post('/tasks').send({ title: ' ' });
expect(whitespace.status).toBe(400);

const list = await request(app).get('/tasks');
expect(list.body).toHaveLength(0);
});

it.each([
['a number', 123],
['null', null],
['a boolean', true],
['an array', []],
['an object', {}],
])('rejects a non-string title (%s) with 400 and creates no task', async (_label, title) => {
const app = createApp();

const res = await request(app).post('/tasks').send({ title });
expect(res.status).toBe(400);
expect(res.body.error).toContain('title');

const list = await request(app).get('/tasks');
expect(list.body).toHaveLength(0);
});

it('marks a task completed via PATCH', async () => {
const app = createApp();
const created = await request(app).post('/tasks').send({ title: 'Finish slides' });
Expand Down
9 changes: 6 additions & 3 deletions sample-app/src/tasks/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,10 +10,13 @@ export function createTaskRouter(store: TaskStore): Router {
});

router.post('/', (req, res) => {
// Exercise 1: validate that req.body.title is a non-empty string and
// return 400 with a helpful message when it is not.
const { title } = req.body ?? {};
const task = store.create(title);
if (typeof title !== 'string' || title.trim().length === 0) {
return res
.status(400)
.json({ error: 'title is required and must be a non-empty string' });
}
const task = store.create(title.trim());
res.status(201).json(task);
});

Expand Down
Loading