[英]How to check value of useRef.current.selectionStart in jest test
一旦在与输入的onKeyDown
交互中更改了useRef.current.selectionStart
和useRef.current.selectionEnd
的值,我需要测试它们。
索引.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
})
})
任何的意见都将会有帮助。
我检查了你的代码。 可能无法在测试用例文件中检查 useRef。 请检查下图 [![在此处输入图像描述并分享该文档链接,以便对您有所帮助。
文档链接: https : //testing-library.com/docs/guiding-principles/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.