|
| 1 | +import * as logs from '../../../../src/logs'; |
| 2 | +import { handleWebhookEvents } from '../../../../src/handlers/webhook-events'; |
| 3 | +import * as httpMocks from 'node-mocks-http'; |
| 4 | + |
| 5 | +// Firebase functions will add rawBody to the request object before it reaches the handler |
| 6 | +declare module 'express' { |
| 7 | + interface Request { |
| 8 | + rawBody: Buffer; |
| 9 | + } |
| 10 | +} |
| 11 | + |
| 12 | +jest.mock('../../../../src/logs', () => ({ |
| 13 | + startWebhookEventProcessing: jest.fn(), |
| 14 | + webhookHandlerError: jest.fn(), |
| 15 | + webhookHandlerSucceeded: jest.fn(), |
| 16 | + badWebhookSecret: jest.fn(), |
| 17 | +})); |
| 18 | + |
| 19 | +jest.mock('../../../../src/config', () => ({ |
| 20 | + stripeWebhookSecret: 'test-webhook-secret', |
| 21 | + customersCollectionPath: 'customers', |
| 22 | + stripe: { |
| 23 | + webhooks: { |
| 24 | + constructEvent: jest.fn(), |
| 25 | + }, |
| 26 | + paymentIntents: { |
| 27 | + retrieve: jest.fn(), |
| 28 | + }, |
| 29 | + }, |
| 30 | + eventChannel: null, |
| 31 | +})); |
| 32 | + |
| 33 | +jest.mock('firebase-admin', () => ({ |
| 34 | + initializeApp: jest.fn(), |
| 35 | + firestore: jest.fn(() => { |
| 36 | + throw new Error('Firestore operation failed'); |
| 37 | + }), |
| 38 | +})); |
| 39 | + |
| 40 | +describe('Webhook Events Handler', () => { |
| 41 | + beforeEach(() => { |
| 42 | + jest.clearAllMocks(); |
| 43 | + |
| 44 | + const config = require('../../../../src/config'); |
| 45 | + config.stripe.webhooks.constructEvent.mockReturnValue({ |
| 46 | + id: 'evt_123', |
| 47 | + type: 'product.created', |
| 48 | + data: { |
| 49 | + object: { id: 'prod_123' }, |
| 50 | + }, |
| 51 | + }); |
| 52 | + }); |
| 53 | + |
| 54 | + it('should return 500 status when webhook handler fails', async () => { |
| 55 | + const mockRequest = httpMocks.createRequest({ |
| 56 | + rawBody: Buffer.from('test-body'), |
| 57 | + headers: { |
| 58 | + 'stripe-signature': 'test-signature', |
| 59 | + }, |
| 60 | + }); |
| 61 | + |
| 62 | + const mockResponse = httpMocks.createResponse(); |
| 63 | + |
| 64 | + await handleWebhookEvents(mockRequest, mockResponse); |
| 65 | + |
| 66 | + expect(logs.webhookHandlerError).toHaveBeenCalledWith( |
| 67 | + expect.any(Error), |
| 68 | + 'evt_123', |
| 69 | + 'product.created' |
| 70 | + ); |
| 71 | + |
| 72 | + expect(mockResponse.statusCode).toBe(500); |
| 73 | + |
| 74 | + const responseData = JSON.parse(mockResponse._getData()); |
| 75 | + expect(responseData).toEqual({ |
| 76 | + error: 'Webhook handler failed. View function logs in Firebase.', |
| 77 | + }); |
| 78 | + }); |
| 79 | +}); |
0 commit comments