|
| 1 | +import * as React from 'react'; |
| 2 | +import { render, screen } from '@testing-library/react'; |
| 3 | +import { DocumentProvider, useDocument } from './DocumentContext'; |
| 4 | + |
| 5 | +// Test component that uses the document context |
| 6 | +function TestComponent() { |
| 7 | + const doc = useDocument(); |
| 8 | + return <div>Has document: {doc ? 'true' : 'false'}</div>; |
| 9 | +} |
| 10 | + |
| 11 | +describe('DocumentContext', () => { |
| 12 | + it('provides default document when no custom document is provided', () => { |
| 13 | + render( |
| 14 | + <DocumentProvider> |
| 15 | + <TestComponent /> |
| 16 | + </DocumentProvider> |
| 17 | + ); |
| 18 | + |
| 19 | + expect(screen.getByText('Has document: true')).toBeInTheDocument(); |
| 20 | + }); |
| 21 | + |
| 22 | + it('provides custom document when specified', () => { |
| 23 | + const mockDocument = {} as Document; |
| 24 | + |
| 25 | + function TestDocumentConsumer() { |
| 26 | + const doc = useDocument(); |
| 27 | + return <div>{doc === mockDocument ? 'custom document' : 'default document'}</div>; |
| 28 | + } |
| 29 | + |
| 30 | + render( |
| 31 | + <DocumentProvider document={mockDocument}> |
| 32 | + <TestDocumentConsumer /> |
| 33 | + </DocumentProvider> |
| 34 | + ); |
| 35 | + |
| 36 | + expect(screen.getByText('custom document')).toBeInTheDocument(); |
| 37 | + }); |
| 38 | + |
| 39 | + it('can be nested with different documents', () => { |
| 40 | + const mockDocument1 = { id: 1 } as unknown as Document; |
| 41 | + const mockDocument2 = { id: 2 } as unknown as Document; |
| 42 | + |
| 43 | + function TestDocumentConsumer() { |
| 44 | + const doc = useDocument(); |
| 45 | + return <div>Document ID: {(doc as any).id}</div>; |
| 46 | + } |
| 47 | + |
| 48 | + render( |
| 49 | + <DocumentProvider document={mockDocument1}> |
| 50 | + <div> |
| 51 | + <TestDocumentConsumer /> |
| 52 | + <DocumentProvider document={mockDocument2}> |
| 53 | + <TestDocumentConsumer /> |
| 54 | + </DocumentProvider> |
| 55 | + </div> |
| 56 | + </DocumentProvider> |
| 57 | + ); |
| 58 | + |
| 59 | + expect(screen.getByText('Document ID: 1')).toBeInTheDocument(); |
| 60 | + expect(screen.getByText('Document ID: 2')).toBeInTheDocument(); |
| 61 | + }); |
| 62 | + |
| 63 | + it('provides global document when no value is passed to provider', () => { |
| 64 | + function TestDocumentConsumer() { |
| 65 | + const doc = useDocument(); |
| 66 | + return <div>{doc === globalThis.document ? 'global document' : 'other document'}</div>; |
| 67 | + } |
| 68 | + |
| 69 | + render( |
| 70 | + <DocumentProvider> |
| 71 | + <TestDocumentConsumer /> |
| 72 | + </DocumentProvider> |
| 73 | + ); |
| 74 | + |
| 75 | + expect(screen.getByText('global document')).toBeInTheDocument(); |
| 76 | + }); |
| 77 | +}); |
0 commit comments