• Home
  • Jobs
  • Courses
  • Questions
  • Teachers
  • For business
  • ES/EN

0

28
Views
How to check value of useRef.current.selectionStart in jest test

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.

about 1 month ago ·

Juan Pablo Isaza

1 answers
Answer question

0

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/

enter image description here

about 1 month ago · Juan Pablo Isaza Report
Answer question
Find remote jobs
Loading

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post job Plans Our process Sales
Legal
Terms and conditions Privacy policy
© 2022 PeakU Inc. All Rights Reserved.