|
| 1 | +import { |
| 2 | + safelyAccessDocument, |
| 3 | + safelyAccessDocumentEvent, |
| 4 | +} from '../../src/utils/document' |
| 5 | +import { afterEach, beforeEach, expect, describe, test } from 'vitest' |
| 6 | + |
| 7 | +const originalDocument = globalThis.document |
| 8 | + |
| 9 | +export function getDocumentMock(): Document { |
| 10 | + return {} as Document |
| 11 | +} |
| 12 | + |
| 13 | +describe('safelyAccessDocument', () => { |
| 14 | + describe('global document', () => { |
| 15 | + const mockedDocument = getDocumentMock() |
| 16 | + const originalDocument = globalThis.document |
| 17 | + beforeEach(() => { |
| 18 | + if (typeof globalThis.document === 'undefined') { |
| 19 | + globalThis.document = mockedDocument |
| 20 | + } |
| 21 | + }) |
| 22 | + afterEach(() => { |
| 23 | + if (typeof originalDocument === 'undefined') { |
| 24 | + // @ts-expect-error Just Typings |
| 25 | + delete globalThis.document |
| 26 | + } |
| 27 | + }) |
| 28 | + |
| 29 | + test('get global document when no args are passed', () => { |
| 30 | + const contextDocument = safelyAccessDocument() |
| 31 | + expect(contextDocument).toEqual(mockedDocument) |
| 32 | + }) |
| 33 | + }) |
| 34 | + |
| 35 | + test('get document', () => { |
| 36 | + let givenDocument = {} as Document |
| 37 | + const contextDocument = safelyAccessDocument(givenDocument) |
| 38 | + |
| 39 | + expect(contextDocument).toEqual(givenDocument) |
| 40 | + }) |
| 41 | +}) |
| 42 | + |
| 43 | +describe('safelyAccessDocumentEvent', () => { |
| 44 | + test('get document by given event', () => { |
| 45 | + const fakeDocument = {} |
| 46 | + const event = new Event('mousedown') |
| 47 | + |
| 48 | + class FakeElement extends EventTarget { |
| 49 | + ownerDocument = fakeDocument |
| 50 | + } |
| 51 | + |
| 52 | + Object.defineProperty(event, 'target', { value: new FakeElement() }) |
| 53 | + |
| 54 | + const document = safelyAccessDocumentEvent(event) |
| 55 | + expect(fakeDocument).toEqual(document) |
| 56 | + }) |
| 57 | +}) |
0 commit comments