← back to Dear Bubbe Nextjs

archived/tests/test-email.js

162 lines

#!/usr/bin/env node

/**
 * Test script for the Welcome Email System
 * This tests the email generation and saving functionality
 */

const http = require('http')

function makeRequest(method, path, data = null) {
  return new Promise((resolve, reject) => {
    const options = {
      hostname: 'localhost',
      port: 3011,
      path: path,
      method: method,
      headers: {
        'Content-Type': 'application/json',
      }
    }
    
    const req = http.request(options, (res) => {
      let body = ''
      
      res.on('data', (chunk) => {
        body += chunk
      })
      
      res.on('end', () => {
        try {
          const json = JSON.parse(body)
          resolve(json)
        } catch (e) {
          resolve({ error: 'Invalid JSON response', body })
        }
      })
    })
    
    req.on('error', (error) => {
      reject(error)
    })
    
    if (data) {
      req.write(JSON.stringify(data))
    }
    
    req.end()
  })
}

async function testWelcomeEmail() {
  console.log('🧪 Testing Welcome Email System...\n')
  
  // Test data
  const testData = {
    to: 'test@example.com',
    name: 'Moshe Cohen',
    userId: 'test-user-123',
    profile: {
      location: 'Brooklyn, NY',
      relationshipStatus: 'single',
      hasKids: 'no',
      religiousLevel: 'somewhat',
      age: 32
    }
  }
  
  try {
    // Test 1: Send welcome email
    console.log('📧 Test 1: Sending welcome email...')
    const result = await makeRequest('POST', '/api/send-welcome-email', testData)
    
    if (result.success) {
      console.log('✅ Email sent successfully!')
      console.log(`   Email ID: ${result.emailId}`)
      console.log(`   Sent to: ${result.to}`)
    } else {
      console.error('❌ Failed to send email:', result.error || result)
      return
    }
    
    // Test 2: Retrieve email history
    console.log('\n📋 Test 2: Retrieving email history...')
    const history = await makeRequest('GET', '/api/send-welcome-email?email=' + testData.to)
    
    if (history.success) {
      console.log(`✅ Found ${history.count} email(s)`)
      history.emails.forEach((email, index) => {
        console.log(`   ${index + 1}. ${email.type} - ${email.to} - ${email.sentAt}`)
      })
    } else {
      console.error('❌ Failed to retrieve history:', history.error || history)
    }
    
    // Test 3: Send another email with minimal data
    console.log('\n📧 Test 3: Sending email with minimal data...')
    const minimalResult = await makeRequest('POST', '/api/send-welcome-email', {
      to: 'minimal@test.com'
    })
    
    if (minimalResult.success) {
      console.log('✅ Minimal email sent successfully!')
      console.log(`   Email ID: ${minimalResult.emailId}`)
    } else {
      console.error('❌ Failed to send minimal email:', minimalResult.error || minimalResult)
    }
    
    // Test 4: Error handling - missing email
    console.log('\n🔥 Test 4: Testing error handling...')
    const errorResult = await makeRequest('POST', '/api/send-welcome-email', {})
    
    if (!errorResult.success) {
      console.log('✅ Error handling works correctly:', errorResult.error)
    } else {
      console.error('❌ Error handling failed - should have returned an error')
    }
    
    // Test 5: Send email with different profiles
    console.log('\n📧 Test 5: Testing different user profiles...')
    
    const profiles = [
      {
        to: 'married.with.kids@example.com',
        name: 'Sarah Goldstein',
        profile: {
          location: 'Los Angeles, CA',
          relationshipStatus: 'married',
          hasKids: 'yes',
          religiousLevel: 'very'
        }
      },
      {
        to: 'single.atheist@example.com',
        name: 'David Rosenberg',
        profile: {
          location: 'Miami, FL',
          relationshipStatus: 'single',
          hasKids: 'no',
          religiousLevel: 'atheist'
        }
      }
    ]
    
    for (const profileData of profiles) {
      const result = await makeRequest('POST', '/api/send-welcome-email', profileData)
      if (result.success) {
        console.log(`✅ Sent to ${profileData.to} (${profileData.profile.relationshipStatus}, ${profileData.profile.hasKids === 'yes' ? 'has kids' : 'no kids'})`)
      }
    }
    
    console.log('\n✨ All tests completed!')
    console.log('\n📂 Check the email files at: /root/Projects/dear-bubbe-nextjs/data/emails/')
    console.log('💡 Run "node view-emails.js" to see all saved emails')
    
  } catch (error) {
    console.error('❌ Test failed:', error.message)
    console.error('Make sure the Next.js server is running on port 3011')
  }
}

// Run the test
testWelcomeEmail()