我有一个自定义钩子(Hook),它可以将可选的 ref 作为对象的属性传递给它,该钩子(Hook)将其作为参数:
export const useShortcuts = ({ ref }) => {
useEffect(() => {
const trapper = new mousetrap(ref.current);
代码有效,但我现在尝试使用
react-testing-library
编写测试。和 @testing-library/react-hooks图书馆。我正在使用
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
});
});
最佳答案
您可以使用 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)
})
关于reactjs - 如何测试可以将html元素的引用传递给它的 react 钩子(Hook),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57350205/