Code to be tested:
export default function handler(req, res) {
try {
if (req.method === 'GET') {
res.setHeader('Content-Type', 'application/json');
res.status(200).json({ message: "hello" });
} else {
res.setHeader('Allow', ['GET']);
res.status(405).json({ error: `Method ${req.method} Not Allowed` });
}
} catch (error) {
console.error('Error handling /api/test:', error);
res.status(500).json({ error: 'Internal Server Error' });
}
}Test Code:
import http from 'http';
import handler from './hello';
// BASE_URL = process.env.TEST_BASE_URL || 'http://localhost:3000';
const BASE_URL = 'https://fireflies.forgefx.tools/api';
describe('GET /api/hello', () => {
let server;
beforeAll(() => {
server = http.createServer(handler);
server.listen(3000);
});
afterAll((done) => {
server.close(done);
});
it('should return 200 with correct message for GET request', async () => {
const url = `${BASE_URL}/hello`;
const response = await fetch(url);
const data = await response.json();
expect(response.status).toBe(200);
expect(data).toEqual({ message: "hello" });
});
it('should return 405 for non-GET methods', async () => {
const response = await fetch(`${BASE_URL}/hello`, { method: 'POST' });
expect(response.status).toBe(405);
const data = await response.text();
expect(data).toContain('Method POST Not Allowed');
});
});