|
| 1 | +import { vi, describe, it, expect } from 'vitest'; |
| 2 | + |
| 3 | +import { isWrappedIframeMessage, makeHandledCallback } from './shared'; |
| 4 | + |
| 5 | +describe('shared', () => { |
| 6 | + describe('isWrappedIframeMessage', () => { |
| 7 | + it('returns true for valid messages', () => { |
| 8 | + expect( |
| 9 | + isWrappedIframeMessage({ |
| 10 | + id: '1', |
| 11 | + message: { type: 'evaluate', data: '1 + 1' }, |
| 12 | + }), |
| 13 | + ).toBe(true); |
| 14 | + }); |
| 15 | + |
| 16 | + it('returns false for invalid messages', () => { |
| 17 | + const invalidMessages = [ |
| 18 | + {}, |
| 19 | + { id: '1' }, |
| 20 | + { message: { type: 'evaluate' } }, |
| 21 | + { id: '1', message: { type: 'evaluate' } }, |
| 22 | + { id: '1', message: { type: 'evaluate', data: 1 } }, |
| 23 | + ]; |
| 24 | + |
| 25 | + invalidMessages.forEach((message) => { |
| 26 | + expect(isWrappedIframeMessage(message)).toBe(false); |
| 27 | + }); |
| 28 | + }); |
| 29 | + }); |
| 30 | + |
| 31 | + describe('makeHandledCallback', () => { |
| 32 | + it('returns a function', () => { |
| 33 | + const callback = makeHandledCallback(async () => Promise.resolve()); |
| 34 | + expect(callback).toBeInstanceOf(Function); |
| 35 | + }); |
| 36 | + |
| 37 | + it('calls the original callback', () => { |
| 38 | + const originalCallback = vi.fn().mockResolvedValueOnce(undefined); |
| 39 | + const callback = makeHandledCallback(originalCallback); |
| 40 | + |
| 41 | + // eslint-disable-next-line n/callback-return |
| 42 | + callback(); |
| 43 | + |
| 44 | + expect(originalCallback).toHaveBeenCalledOnce(); |
| 45 | + }); |
| 46 | + |
| 47 | + it('throws an error if the original callback throws an error', async () => { |
| 48 | + const consoleErrorSpy = vi.spyOn(console, 'error'); |
| 49 | + const error = new Error('test error'); |
| 50 | + const originalCallback = vi.fn().mockRejectedValueOnce(error); |
| 51 | + const callback = makeHandledCallback(originalCallback); |
| 52 | + |
| 53 | + // eslint-disable-next-line n/callback-return |
| 54 | + callback(); |
| 55 | + // eslint-disable-next-line @typescript-eslint/await-thenable |
| 56 | + await null; |
| 57 | + |
| 58 | + expect(consoleErrorSpy).toHaveBeenCalledOnce(); |
| 59 | + expect(consoleErrorSpy).toHaveBeenCalledWith( |
| 60 | + expect.objectContaining({ message: error.message }), |
| 61 | + ); |
| 62 | + }); |
| 63 | + }); |
| 64 | +}); |
0 commit comments