contact-api.int.spec.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import { beforeEach, describe, expect, it, vi } from 'vitest'
  2. import { POST } from '@/app/api/contact/route'
  3. import { sendEmail } from '@/lib/mailer'
  4. vi.mock('@/lib/mailer', () => ({
  5. sendEmail: vi.fn(),
  6. }))
  7. describe('Contact API', () => {
  8. beforeEach(() => {
  9. vi.clearAllMocks()
  10. process.env.CONTACT_TO_EMAIL = 'internal-team@example.com'
  11. })
  12. it('returns success for valid payload', async () => {
  13. vi.mocked(sendEmail).mockResolvedValue(undefined)
  14. const request = new Request('http://localhost:3001/api/contact', {
  15. method: 'POST',
  16. headers: {
  17. 'Content-Type': 'application/json',
  18. },
  19. body: JSON.stringify({
  20. name: ' John Doe ',
  21. email: ' JOHN@EXAMPLE.COM ',
  22. phone: ' +62 812-1111-2222 ',
  23. message: ' Hello team, I need more information. ',
  24. }),
  25. })
  26. const response = await POST(request)
  27. const body = await response.json()
  28. expect(response.status).toBe(200)
  29. expect(body).toEqual({
  30. ok: true,
  31. message: 'Message sent',
  32. })
  33. expect(sendEmail).toHaveBeenCalledTimes(1)
  34. expect(sendEmail).toHaveBeenCalledWith({
  35. to: 'internal-team@example.com',
  36. subject: '[Website] New Contact Message from John Doe',
  37. text: expect.stringContaining('Name: John Doe'),
  38. replyTo: 'john@example.com',
  39. })
  40. })
  41. it('returns validation error for invalid payload', async () => {
  42. const request = new Request('http://localhost:3001/api/contact', {
  43. method: 'POST',
  44. headers: {
  45. 'Content-Type': 'application/json',
  46. },
  47. body: JSON.stringify({
  48. name: 'Jane',
  49. email: 'invalid-email',
  50. message: '',
  51. }),
  52. })
  53. const response = await POST(request)
  54. const body = await response.json()
  55. expect(response.status).toBe(400)
  56. expect(body).toEqual({
  57. ok: false,
  58. error: 'Validation error',
  59. })
  60. expect(sendEmail).not.toHaveBeenCalled()
  61. })
  62. })