File size: 1,370 Bytes
1fe7075
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import type Stripe from 'stripe';
import type { SubscriptionsService } from '../subscriptions/subscriptions.service.js';
import { WebhooksService } from './webhooks.service.js';

const event = (type: string, object: object) => ({ type, data: { object } }) as unknown as Stripe.Event;

describe('WebhooksService', () => {
  const subscriptions = { syncFromStripe: vi.fn() };
  const service = new WebhooksService(subscriptions as unknown as SubscriptionsService);

  beforeEach(() => vi.clearAllMocks());

  it.each(['customer.subscription.created', 'customer.subscription.updated', 'customer.subscription.deleted'])(
    'syncs the subscription on %s',
    async (type) => {
      await service.handle(event(type, { id: 'sub_1' }));
      expect(subscriptions.syncFromStripe).toHaveBeenCalledWith('sub_1');
    },
  );

  it('syncs the subscription a completed checkout created', async () => {
    await service.handle(event('checkout.session.completed', { subscription: 'sub_2' }));
    expect(subscriptions.syncFromStripe).toHaveBeenCalledWith('sub_2');
  });

  it('ignores other events and checkouts without a subscription', async () => {
    await service.handle(event('invoice.paid', { id: 'in_1' }));
    await service.handle(event('checkout.session.completed', { subscription: null }));
    expect(subscriptions.syncFromStripe).not.toHaveBeenCalled();
  });
});