11import React from "react" ;
2- import { render , fireEvent , flushEffects } from "react-testing-library" ;
2+ import {
3+ cleanup ,
4+ render ,
5+ fireEvent ,
6+ flushEffects
7+ } from "react-testing-library" ;
38import { ModalProvider , useModal } from ".." ;
49import "jest-dom/extend-expect" ;
510
11+ afterEach ( cleanup ) ;
12+
13+ beforeEach ( ( ) => {
14+ jest . spyOn ( console , "error" ) ;
15+ ( global . console . error as any ) . mockImplementation ( ( ) => { } ) ;
16+ } ) ;
17+
18+ afterEach ( ( ) => {
19+ ( global . console . error as any ) . mockRestore ( ) ;
20+ } ) ;
21+
622describe ( "custom container prop" , ( ) => {
7- const Container : React . SFC = ( { children } ) => (
8- < div data-testid = "custom-container " > { children } </ div >
23+ const RootComponent : React . SFC = ( { children } ) => (
24+ < div data-testid = "custom-root " > { children } </ div >
925 ) ;
1026
1127 const App = ( ) => {
@@ -14,18 +30,52 @@ describe("custom container prop", () => {
1430 return < button onClick = { showModal } > Show modal</ button > ;
1531 } ;
1632
17- it ( "should render modals inside custom container " , ( ) => {
33+ it ( "should render modals inside custom root component " , ( ) => {
1834 const { getByTestId, getByText } = render (
19- < ModalProvider container = { Container } >
35+ < ModalProvider rootComponent = { RootComponent } >
2036 < App />
2137 </ ModalProvider >
2238 ) ;
2339
2440 fireEvent . click ( getByText ( "Show modal" ) ) ;
2541 flushEffects ( ) ;
2642
27- expect ( getByTestId ( "custom-container " ) ) . toContainElement (
43+ expect ( getByTestId ( "custom-root " ) ) . toContainElement (
2844 getByText ( "This is a modal" )
2945 ) ;
3046 } ) ;
47+
48+ it ( "should render modals inside the specified root element" , ( ) => {
49+ const customRoot = document . createElement ( "div" ) ;
50+
51+ document . body . appendChild ( customRoot ) ;
52+
53+ const { getByText } = render (
54+ < ModalProvider container = { customRoot } >
55+ < App />
56+ </ ModalProvider >
57+ ) ;
58+
59+ fireEvent . click ( getByText ( "Show modal" ) ) ;
60+ flushEffects ( ) ;
61+
62+ expect ( customRoot ) . toContainElement ( getByText ( "This is a modal" ) ) ;
63+ } ) ;
64+
65+ it ( "should throw an error when `container` does not specify a DOM elemnet" , ( ) => {
66+ expect ( ( ) => {
67+ render (
68+ < ModalProvider container = { React . Fragment as any } >
69+ < App />
70+ </ ModalProvider >
71+ ) ;
72+ flushEffects ( ) ;
73+ } ) . toThrowError (
74+ expect . objectContaining ( {
75+ message : expect . stringMatching (
76+ / C o n t a i n e r m u s t s p e c i f y D O M e l e m e n t t o m o u n t m o d a l r o o t i n t o /
77+ )
78+ } )
79+ ) ;
80+ } ) ;
3181} ) ;
0 commit comments