我创建了这个useHover钩子:
import { useRef, useState, useEffect } from 'react';
export const useHover = () => {
const [value, setValue] = useState(false);
const ref = useRef(null);
const handleMouseOver = () => setValue(true);
const handleMouseOut = () => setValue(false);
useEffect(
// eslint-disable-next-line consistent-return
() => {
const node = ref.current;
if (node) {
node.addEventListener('mouseover', handleMouseOver);
node.addEventListener('mouseout', handleMouseOut);
return () => {
node.removeEventListener('mouseover', handleMouseOver);
node.removeEventListener('mouseout', handleMouseOut);
};
}
},
[]
);
return [ref, value];
};
我写了这个测试:
import React from 'react';
import { renderHook } from '@testing-library/react-hooks';
import { fireEvent, render } from '@testing-library/react';
import { Box } from 'gestalt';
import userEvent from '@testing-library/user-event';
import { useHover } from './useHover';
describe('useHover', () => {
it('toogles', async () => {
const { result } = renderHook(() => useHover());
// eslint-disable-next-line no-unused-vars
const [ref, value] = result.current;
expect(value).toBeFalsy();
const Div = () => <Box ref={ref}>Test</Box>;
render(<Div />);
await userEvent.hover(ref.current);
expect(value).toBeTruthy();
fireEvent.mouseOut(ref.current);
expect(value).toBeFalsy();
});
});
但是失败了:
21 | Expect(value).toBeTruthy();
答案 0 :(得分:0)
乍一看,我看到了一些可能的问题