import React from'react'import{ CSSTransition }from'react-transition-group'import{ render, fireEvent }from'@testing-library/react'functionFade({ children,...props }){return(<CSSTransition{...props}timeout={1000}className="fade">{children}</CSSTransition>)}classHiddenMessageextendsReact.Component{
state ={ show:this.props.initialShow ||false}toggle=()=>{this.setState(({ show })=>({ show:!show }))}render(){return(<div><buttononClick={this.toggle}>Toggle</button><Fadein={this.state.show}><div>Hello world</div></Fade></div>)}}
jest.mock('react-transition-group',()=>{const FakeTransition = jest.fn(({ children })=> children)const FakeCSSTransition = 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 message
fireEvent.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
import React from'react'import{ CSSTransition }from'react-transition-group'import{ render, fireEvent }from'@testing-library/react'functionFade({ children,...props }){return(<CSSTransition{...props}timeout={1000}className="fade">{children}</CSSTransition>)}classHiddenMessageextendsReact.Component{
state ={ show:this.props.initialShow ||false}toggle=()=>{this.setState(({ show })=>({ show:!show }))}render(){return(<div><buttononClick={this.toggle}>Toggle</button><Fadein={this.state.show}><div>Hello world</div></Fade></div>)}}
jest.mock('react-transition-group',()=>{const FakeCSSTransition = jest.fn(()=>null)return{ CSSTransition: FakeCSSTransition }})test('you can mock things with jest.mock',()=>{const{ getByText }=render(<HiddenMessageinitialShow={true}/>)const context = expect.any(Object)const children = expect.any(Object)const defaultProps ={ children, timeout:1000, className:'fade'}expect(CSSTransition).toHaveBeenCalledWith({in:true,...defaultProps },
context
)
fireEvent.click(getByText(/toggle/i))expect(CSSTransition).toHaveBeenCalledWith({in:true,...defaultProps },
expect.any(Object))})