diff --git a/tests/formDataServer.test.js b/tests/formDataServer.test.js index 0ee1766..a9e2b2a 100644 --- a/tests/formDataServer.test.js +++ b/tests/formDataServer.test.js @@ -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 }); @@ -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(' { fs.writeFileSync(dataPath, JSON.stringify({})); const expense = { @@ -56,7 +68,7 @@ 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 = { @@ -64,27 +76,38 @@ describe('Form Data Server', () => { 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(''); + expect(response.data).toContain(JSON.stringify(expense, null, 2)); }); it('should return 404 for invalid url', async () => {