4

我有一个自定义钩子,它可以将可选的 ref 作为对象的属性传递给它,该钩子将其作为参数:

export const useShortcuts = ({ ref }) => {
  useEffect(() => {
    const trapper = new mousetrap(ref.current);

该代码有效,但我现在正在尝试使用 @testing-library/react-hooks 库为此react-testing-library编写测试

我正在使用renderHook@ testing-library/react-hooks,但我不知道如何在组件外部创建引用或模拟引用。

  it('should create shortcuts with no ref', () => {
    const ref = ?????  // how do I do this

    const { result } = renderHook(() => useShortcuts({ ref }), {
      initialProps: true
    });
  });
4

2 回答 2

6

您可以使用React.createRef

const ref = React.createRef()

下面的完整工作示例

import React, { useEffect } from 'react'
import { renderHook } from '@testing-library/react-hooks'

const useShortcuts = ({ ref }) => {
  useEffect(() => {
    ref.current = 1
  }, [])
}


it('works', () => {
  const ref = React.createRef()

  const { result } = renderHook(() => useShortcuts({ ref }))
  expect(ref.current).toEqual(1)
})
于 2019-08-04T21:42:38.993 回答
1

一种类型安全的方法(因为在 TypeScript 中 createRef 返回一个只读对象),就是放弃这个createRef想法,只创建一个具有current属性的对象:

it('should create shortcuts with no ref', () => {
  const ref = { current: undefined }

  const { result } = renderHook(() => useShortcuts({ ref }), {
    initialProps: true
  });
});

或者如果你想传递一个元素:

const elem = document.createElement('div');
const ref = { current: elem };

如果钩子是预期的,后者应该足以作为 TypeScript 的类型:

ref: React.RefObject<HTMLElement>
于 2021-02-04T21:50:04.787 回答