I need to test the values of useRef.current.selectionStart
and useRef.current.selectionEnd
once they have been changed on a onKeyDown
interaction with an input.
index.tsx
import React, { useRef, useEffect } from 'react'
type Props {
value: string
...aBunchOfProps
}
const SomeComponent: FC<Props> = ({ value, ...aBunchOfProps }) => {
const inputRef = useRef(null)
const [caretPosition, setCaretPosition] = useState<CaretPosition | undefined>()
useEffect(() => {
if (!!caretPosition && !!value) {
let newCaretPosition = caretPosition.currentPosition
const shouldMoveCaretForward =
caretPosition.direction === 1 && value.charAt(caretPosition.currentPosition) === '/'
if (shouldMoveCaretForward) {
newCaretPosition++
}
inputRef.current.selectionStart = newCaretPosition <=== this is the line I want to test
inputRef.current.selectionEnd = newCaretPosition <=== this is the line I want to test
}
}, [caretPosition])
const someFunction = () => {
// calls setCaretPosition with new details
}
return (
...someAdditionalCode
<input
...someAdditionalProps
ref={inputRef}
value={value}
data-testid="input-field"
onKeyDown={() => someFuction()}
/>
...evenMoreCode
)
}
export default SomeComponent
index.test.tsx
describe('SomeComponent tests', () => {
it('should move cursor correctly', () => {
const { getByTestId } = render(<SomeComonent value="12/3" />)
const input = getByTestId('input-field')
fireEvent.keyDown(input, { key: '4' })
// expect(useRef.current.selectionStart).toEqual(5) <==== I want something like this
// expect(useRef.current.selectionEnd).toEqual(5) <==== I want something like this
})
})
Any suggestions would be helpful.
Juan Pablo Isaza
I had checked your code. It May be not possible to check useRef in testcase file. please check shown below image [![enter image description here and also share that document link, so it can be helpful to you.
document link: https://testing-library.com/docs/guiding-principles/