'How to unit test a forwardRef-wrapped component with react-testing-library?

forwardRef-wrapped component doesn't seem to set the ref as the following test fails with this error:

    Error: Uncaught [TypeError: Cannot read properties of null (reading 'focus')]

It works in the browser, only the test fails.

The component:

export const SelectFormItem = forwardRef(
  <VT extends SelectValue = SelectValue>(
    { name, label, rules }: Props<VT>,
    ref: React.Ref<RefSelectProps>
  ) => {

    return (
      <Form.Item name={name} label={label} rules={rules}>
          <Select ref={ref} />
      </Form.Item>
    )
  }
)
SelectFormItem.displayName = 'SelectFormItem'

The failing test:

describe('BEHAVIOR', () => {
  test('ref.current.focus() sets focus on component', () => {
    const Wrapper = () => {
      const ref = useRef<RefSelectProps>(null)
      return (
        <Form initialValues={{ value: 'Value 1' }}>
          <SelectFormItem mode='multiple' name={'value'} label={'TheValue'} options={Options} readOnly={true} ref={ref}/>
          <Button onClick={() => ref.current.focus()}>Focus</Button>
        </Form>
      )
    }

    render(<Wrapper />)
    screen.getByText('Focus').click()
  })
})


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source