jest-environment import * as React from 'react' ; import { render , fireEvent } from '@testing-library/react' ; import userEvent from '@testing-library/user-event' ; import useStateForModelWithValidation from './useStateForModelWithValidation' ; const validationsComment = ( propName , propValue ) => { switch ( propName ) { case 'Comment' : return propValue && propValue . length > 0 ? '' : 'Error' ; default : return '' ; } } ; const TestComponent = ( ) => { const [ model , onChange , isValid , error ] = useStateForModelWithValidation ( { Comment : '' } , validationsComment ) ; const _onClick = ( event ) => 'I have been submitted' ; return ( < > < input type = "text" data - testid = "Comment" name = "Comment" value = { model . Comment } onChange = { onChange } / > < span data - testid = "error" > { error . Comment } < /span> < button type = "submit" disabled = { ! isValid } onClick = { _onClick } > Submit < /button> < />); } ; describe ( 'Tests for useStateForModelWithValidation hook' , ( ) => { it ( 'Disabled button, error does not exist' , ( ) => { const { getByText , getByTestId } = render ( < TestComponent />); const input = getByTestId ( 'Comment' ) ; const button = getByText ( 'Submit' ) ; const error = getByTestId ( 'error' ) ; expect ( input ) . toHaveValue ( '' ) ; expect ( error ) . not . toBeEmptyDOMElement ( ) ; expect ( button ) . toBeDisabled ( ) ; } ) ; it ( 'Add text, error does not exist' , async ( ) => { const { getByText , getByTestId } = render ( < TestComponent />); const input = getByTestId ( 'Comment' ) ; const button = getByText ( 'Submit' ) ; const error = getByTestId ( 'error' ) ; await userEvent . type ( input , 'Simio is watching' ) ; expect ( input ) . toHaveValue ( 'Simio is watching' ) ; expect ( error ) . toBeEmptyDOMElement ( ) ; expect ( button ) . toBeEnabled ( ) ; } ) ; it ( 'Empty input text, error exists' , async ( ) => { const { getByText , getByTestId } = render ( < TestComponent />); const input = getByTestId ( 'Comment' ) ; const error = getByTestId ( 'error' ) ; const button = getByText ( 'Submit' ) ; await userEvent . type ( input , 'Simio is watching' ) ; fireEvent . change ( input , { target : { value : '' } } ) ; expect ( input ) . toHaveAttribute ( 'value' , '' ) ; expect ( error ) . not . toBeEmptyDOMElement ( ) ; expect ( button ) . toBeDisabled ( ) ; } ) ; } ) ;