Skip to content
Merged
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
39 changes: 31 additions & 8 deletions tests/formDataServer.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const fs = require('fs');
const path = require('path');
const axios = require('axios');
const { Server, Agent } = require('http');
const querystring = require('querystring');

// this prevents `socket hang up` for Node.js 20.10+
axios.defaults.httpAgent = new Agent({ keepAlive: false });
Expand Down Expand Up @@ -39,7 +40,18 @@ describe('Form Data Server', () => {
server.close();
});

it('should save data for valid expense on "POST /submit-expense" request', async () => {
it('should return an HTML form on "GET /" request', async () => {
const response = await axios.get(`${HOST}/`);

expect(response.status).toBe(200);
expect(response.headers['content-type']).toContain('text/html');
expect(response.data).toContain('<form');
expect(response.data).toContain('name="date"');
expect(response.data).toContain('name="title"');
expect(response.data).toContain('name="amount"');
});

it('should save data for valid expense on "POST /add-expense" request', async () => {
fs.writeFileSync(dataPath, JSON.stringify({}));

const expense = {
Expand All @@ -56,35 +68,46 @@ describe('Form Data Server', () => {
expect(savedData).toStrictEqual(expense);
});

it('should reject request without all params on "POST /submit-expense" request', async () => {
it('should reject request without all params on "POST /add-expense" request', async () => {
fs.writeFileSync(dataPath, JSON.stringify({}));

const expense = {
title: 'Invalid Expense',
amount: '100',
};

expect.assertions(2);
expect.assertions(3);

try {
await axios.post(`${HOST}/add-expense`, expense);
} catch (err) {
expect(err.response.status).toBe(400);
expect(err.response.data.length).toBeGreaterThan(0);

expect(JSON.parse(fs.readFileSync(dataPath))).toStrictEqual({});
}
});

it('should return JSON on "POST /submit-expense" request', async () => {
it('should return HTML with formatted JSON on "POST /add-expense" request', async () => {
const expense = {
date: '2024-01-25',
title: 'Test Expense',
amount: '100',
};
const response = await axios.post(`${HOST}/add-expense`, expense);

expect(response.headers['content-type']).toBe('application/json');
expect(response.data).toStrictEqual(expense);
const response = await axios.post(
`${HOST}/add-expense`,
querystring.stringify(expense),
{
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
},
);

expect(response.headers['content-type']).toContain('text/html');
expect(response.data).toContain('<html');
expect(response.data).toContain('<pre>');
expect(response.data).toContain(JSON.stringify(expense, null, 2));
});

it('should return 404 for invalid url', async () => {
Expand Down
Loading