|
| 1 | +import type { ExecutionContext } from '@cloudflare/workers-types'; |
| 2 | +import { afterEach, describe, expect, it, vi } from 'vitest'; |
| 3 | +import { withSentry } from '../src/withSentry'; |
| 4 | +import { resetSdk } from './testUtils'; |
| 5 | + |
| 6 | +const MOCK_ENV = { |
| 7 | + SENTRY_DSN: 'https://public@dsn.ingest.sentry.io/1337', |
| 8 | +}; |
| 9 | + |
| 10 | +function createMockExecutionContext(): ExecutionContext { |
| 11 | + return { |
| 12 | + waitUntil: vi.fn(), |
| 13 | + passThroughOnException: vi.fn(), |
| 14 | + props: {}, |
| 15 | + } as unknown as ExecutionContext; |
| 16 | +} |
| 17 | + |
| 18 | +class WorkerEntrypoint { |
| 19 | + public constructor( |
| 20 | + public ctx: ExecutionContext, |
| 21 | + public env: unknown, |
| 22 | + ) {} |
| 23 | +} |
| 24 | + |
| 25 | +describe('withSentry', () => { |
| 26 | + afterEach(() => { |
| 27 | + vi.restoreAllMocks(); |
| 28 | + resetSdk(); |
| 29 | + }); |
| 30 | + |
| 31 | + it('returns the same handler object with its methods wrapped', () => { |
| 32 | + const fetch = vi.fn(); |
| 33 | + const handler = { fetch }; |
| 34 | + |
| 35 | + const wrapped = withSentry(() => ({}), handler); |
| 36 | + |
| 37 | + expect(wrapped).toBe(handler); |
| 38 | + expect(wrapped.fetch).not.toBe(fetch); |
| 39 | + }); |
| 40 | + |
| 41 | + it('instruments a WorkerEntrypoint class instead of treating it as a handler object', () => { |
| 42 | + class MyEntrypoint extends WorkerEntrypoint { |
| 43 | + public ping(): string { |
| 44 | + return 'pong'; |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + const optionsCallback = vi.fn().mockReturnValue({ dsn: MOCK_ENV.SENTRY_DSN }); |
| 49 | + const context = createMockExecutionContext(); |
| 50 | + |
| 51 | + const Wrapped = withSentry(optionsCallback, MyEntrypoint as never) as unknown as typeof MyEntrypoint; |
| 52 | + const instance = new Wrapped(context, MOCK_ENV); |
| 53 | + |
| 54 | + expect(Wrapped).not.toBe(MyEntrypoint); |
| 55 | + expect(optionsCallback).toHaveBeenCalledWith(MOCK_ENV); |
| 56 | + expect(instance).toBeInstanceOf(MyEntrypoint); |
| 57 | + expect(instance.ctx).not.toBe(context); |
| 58 | + expect(instance.ping()).toBe('pong'); |
| 59 | + }); |
| 60 | + |
| 61 | + it('returns a handler it cannot instrument unchanged instead of throwing', () => { |
| 62 | + const fetch = vi.fn(); |
| 63 | + const handler = Object.freeze({ fetch }); |
| 64 | + |
| 65 | + let wrapped: typeof handler | undefined; |
| 66 | + expect(() => { |
| 67 | + wrapped = withSentry(() => ({}), handler); |
| 68 | + }).not.toThrow(); |
| 69 | + |
| 70 | + expect(wrapped).toBe(handler); |
| 71 | + expect(wrapped?.fetch).toBe(fetch); |
| 72 | + }); |
| 73 | +}); |
0 commit comments