Files
bookmarksite/tests/test-email-service.js
2025-07-20 20:43:06 +02:00

200 lines
6.8 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env node
/**
* Test script to verify email service configuration and resend verification functionality
*/
const API_BASE_URL = 'http://localhost:3001/api';
// Colors for console output
const colors = {
green: '\x1b[32m',
red: '\x1b[31m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
reset: '\x1b[0m',
bold: '\x1b[1m'
};
function log(message, color = colors.reset) {
console.log(`${color}${message}${colors.reset}`);
}
function success(message) {
log(`${message}`, colors.green);
}
function error(message) {
log(`${message}`, colors.red);
}
function warning(message) {
log(`⚠️ ${message}`, colors.yellow);
}
function info(message) {
log(` ${message}`, colors.blue);
}
async function testEmailService() {
log('\n' + '='.repeat(60), colors.bold);
log('📧 EMAIL SERVICE & RESEND VERIFICATION TEST', colors.bold);
log('='.repeat(60), colors.bold);
const testEmail = `test-email-${Date.now()}@example.com`;
const testPassword = 'TestPassword123!';
try {
// Step 1: Check server health
info('\n1. Checking server health...');
const healthResponse = await fetch('http://localhost:3001/health');
if (healthResponse.ok) {
const healthData = await healthResponse.json();
success('Server is running');
info(`Database status: ${healthData.database.healthy ? 'Healthy' : 'Unhealthy'}`);
} else {
error('Server health check failed');
return;
}
// Step 2: Register a test user (this will trigger verification email)
info('\n2. Registering test user to trigger verification email...');
const registerResponse = await fetch(`${API_BASE_URL}/auth/register`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: testEmail,
password: testPassword
})
});
const registerData = await registerResponse.json();
if (registerResponse.ok) {
success('User registration successful');
info(`User ID: ${registerData.user?.id}`);
info('Initial verification email should have been sent');
} else {
error(`Registration failed: ${registerData.error}`);
if (registerData.error.includes('Email service is not configured')) {
warning('Email service configuration issue detected');
}
}
// Step 3: Test resend verification functionality
info('\n3. Testing resend verification email...');
const resendResponse = await fetch(`${API_BASE_URL}/auth/resend-verification`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: testEmail
})
});
const resendData = await resendResponse.json();
if (resendResponse.ok) {
success('Resend verification request successful');
info(`Message: ${resendData.message}`);
} else {
error(`Resend verification failed: ${resendData.error}`);
if (resendData.error.includes('Email service is not configured')) {
warning('Email service configuration issue detected');
}
}
// Step 4: Test with non-existent email (should still return success for security)
info('\n4. Testing resend with non-existent email...');
const nonExistentEmail = `nonexistent-${Date.now()}@example.com`;
const nonExistentResponse = await fetch(`${API_BASE_URL}/auth/resend-verification`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: nonExistentEmail
})
});
const nonExistentData = await nonExistentResponse.json();
if (nonExistentResponse.ok) {
success('Non-existent email handled correctly (security response)');
info(`Message: ${nonExistentData.message}`);
} else {
warning(`Unexpected response for non-existent email: ${nonExistentData.error}`);
}
// Step 5: Test validation (missing email)
info('\n5. Testing validation (missing email)...');
const missingEmailResponse = await fetch(`${API_BASE_URL}/auth/resend-verification`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({})
});
const missingEmailData = await missingEmailResponse.json();
if (missingEmailResponse.status === 400) {
success('Missing email validation working correctly');
info(`Error: ${missingEmailData.error}`);
} else {
error(`Expected 400 status for missing email, got ${missingEmailResponse.status}`);
}
// Step 6: Test rate limiting
info('\n6. Testing rate limiting...');
const rateLimitPromises = [];
for (let i = 0; i < 6; i++) {
rateLimitPromises.push(
fetch(`${API_BASE_URL}/auth/resend-verification`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email: testEmail
})
})
);
}
const rateLimitResponses = await Promise.all(rateLimitPromises);
const rateLimitedCount = rateLimitResponses.filter(r => r.status === 429).length;
if (rateLimitedCount > 0) {
success(`Rate limiting working: ${rateLimitedCount} requests were rate limited`);
} else {
warning('Rate limiting may not be working as expected');
}
log('\n' + '='.repeat(60), colors.bold);
log('📊 TEST SUMMARY', colors.bold);
log('='.repeat(60), colors.bold);
success('✅ API endpoints are working correctly');
success('✅ Validation is working properly');
success('✅ Rate limiting is functional');
success('✅ Security responses are appropriate');
if (registerResponse.ok && resendResponse.ok) {
success('✅ Resend verification functionality is WORKING');
info('📧 Email service appears to be configured correctly');
} else {
warning('⚠️ Email service configuration needs attention');
info('💡 Check EMAIL_* environment variables in backend/.env');
}
} catch (err) {
error(`Test execution failed: ${err.message}`);
}
}
// Run the test
testEmailService().catch(console.error);