78 lines
3.1 KiB
JavaScript
78 lines
3.1 KiB
JavaScript
const request = require('supertest');
|
|
const app = require('./server'); // Adjust the path if server.js is in another folder
|
|
const nodemailer = require('nodemailer');
|
|
|
|
// ==========================================
|
|
// MOCK EXTERNAL SERVICES
|
|
// ==========================================
|
|
jest.mock('nodemailer');
|
|
|
|
describe('Enterprise Application Flow & API Validation', () => {
|
|
|
|
beforeAll(() => {
|
|
// Configure the mock to simulate a successful SMTP response
|
|
nodemailer.createTransport.mockReturnValue({
|
|
sendMail: jest.fn().mockResolvedValue({ messageId: 'mock-id-enterprise-1234' })
|
|
});
|
|
});
|
|
|
|
afterEach(() => {
|
|
jest.clearAllMocks(); // Clear tracking between tests
|
|
});
|
|
|
|
// ==========================================
|
|
// 1. STATIC ROUTING TESTS
|
|
// ==========================================
|
|
describe('1. Static Web Routing', () => {
|
|
it('Should return 200 OK and text/html for the Home Page (/)', async () => {
|
|
const response = await request(app).get('/');
|
|
expect(response.status).toBe(200);
|
|
expect(response.headers['content-type']).toMatch(/text\/html/);
|
|
});
|
|
|
|
it('Should return 404 Not Found for an unknown endpoint', async () => {
|
|
const response = await request(app).get('/invalid-admin-route');
|
|
expect(response.status).toBe(404);
|
|
});
|
|
});
|
|
|
|
// ==========================================
|
|
// 2. API BUSINESS LOGIC & VALIDATION TESTS
|
|
// ==========================================
|
|
describe('2. Contact API Endpoint (/api/contact)', () => {
|
|
|
|
it('Should reject requests and return 400 Bad Request if email is missing', async () => {
|
|
const invalidPayload = {
|
|
firstName: 'John',
|
|
message: 'I need a security audit.'
|
|
// Missing 'email' deliberately
|
|
};
|
|
|
|
const response = await request(app).post('/api/contact').send(invalidPayload);
|
|
|
|
expect(response.status).toBe(400);
|
|
expect(response.body).toHaveProperty('error', 'Email and message are required.');
|
|
});
|
|
|
|
it('Should process request, return 200 OK, and invoke SMTP transporter with valid data', async () => {
|
|
const validPayload = {
|
|
firstName: 'Jane',
|
|
lastName: 'Doe',
|
|
email: 'jane.doe@example.com',
|
|
company: 'Apex Corporation',
|
|
message: 'Please send me the DevSecOps proposal.'
|
|
};
|
|
|
|
const response = await request(app).post('/api/contact').send(validPayload);
|
|
|
|
// Validate HTTP Response
|
|
expect(response.status).toBe(200);
|
|
expect(response.body).toHaveProperty('success', true);
|
|
expect(response.body.message).toContain('confirmation email has been dispatched');
|
|
|
|
// Validate Business Logic (Verify if the mock function was actually called)
|
|
const mockTransport = nodemailer.createTransport();
|
|
expect(mockTransport.sendMail).toHaveBeenCalledTimes(1);
|
|
});
|
|
});
|
|
}); |