如何在玩笑测试中检查 useRef.current.selectionStart 的值
Posted
技术标签:
【中文标题】如何在玩笑测试中检查 useRef.current.selectionStart 的值【英文标题】:How to check value of useRef.current.selectionStart in jest test 【发布时间】:2021-11-12 02:55:29 【问题描述】:useRef.current.selectionStart
和 useRef.current.selectionEnd
的值在 onKeyDown
与输入交互时发生更改后,我需要对其进行测试。
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
)
)
任何建议都会有所帮助。
【问题讨论】:
【参考方案1】:我已经检查了您的代码。可能无法检查测试用例文件中的 useRef。请检查下面显示的图片[![在此处输入图片描述并分享该文档链接,以便对您有所帮助。
文档链接:https://testing-library.com/docs/guiding-principles/
【讨论】:
以上是关于如何在玩笑测试中检查 useRef.current.selectionStart 的值的主要内容,如果未能解决你的问题,请参考以下文章