Skip to content

Latest commit

 

History

History
102 lines (90 loc) · 2.8 KB

example-react-transition-group.mdx

File metadata and controls

102 lines (90 loc) · 2.8 KB
idtitle
example-react-transition-group
React Transition Group

Mock

importReact,{useState}from'react'import{CSSTransition}from'react-transition-group'import{render,fireEvent}from'@testing-library/react'functionFade({children, ...props}){return(<CSSTransition{...props}timeout={1000}classNames="fade">{children}</CSSTransition>)}functionHiddenMessage({initialShow}){const[show,setShow]=useState(initialShow||false)consttoggle=()=>setShow(prevState=>!prevState)return(<div><buttononClick={toggle}>Toggle</button><Fadein={show}><div>Hello world</div></Fade></div>)}jest.mock('react-transition-group',()=>{constFakeTransition=jest.fn(({children})=>children)constFakeCSSTransition=jest.fn(props=>props.in ? <FakeTransition>{props.children}</FakeTransition> : null,)return{CSSTransition: FakeCSSTransition,Transition: FakeTransition}})test('you can mock things with jest.mock',()=>{const{getByText, queryByText}=render(<HiddenMessageinitialShow={true}/>)expect(getByText('Hello world')).toBeTruthy()// we just care it exists// hide the messagefireEvent.click(getByText('Toggle'))// in the real world, the CSSTransition component would take some time// before finishing the animation which would actually hide the message.// So we've mocked it out for our tests to make it happen instantlyexpect(queryByText('Hello World')).toBeNull()// we just care it doesn't exist})

Shallow

importReact,{useState}from'react'import{CSSTransition}from'react-transition-group'import{render,fireEvent}from'@testing-library/react'functionFade({children, ...props}){return(<CSSTransition{...props}timeout={1000}classNames="fade">{children}</CSSTransition>)}functionHiddenMessage({initialShow}){const[show,setShow]=useState(initialShow||false)consttoggle=()=>setShow(prevState=>!prevState)return(<div><buttononClick={toggle}>Toggle</button><Fadein={show}><div>Hello world</div></Fade></div>)}jest.mock('react-transition-group',()=>{constFakeCSSTransition=jest.fn(()=>null)return{CSSTransition: FakeCSSTransition}})test('you can mock things with jest.mock',()=>{const{getByText}=render(<HiddenMessageinitialShow={true}/>)constcontext=expect.any(Object)constchildren=expect.any(Object)constdefaultProps={children,timeout: 1000,className: 'fade'}expect(CSSTransition).toHaveBeenCalledWith({in: true, ...defaultProps},context,)fireEvent.click(getByText(/toggle/i))expect(CSSTransition).toHaveBeenCalledWith({in: false, ...defaultProps},expect.any(Object),)})
close