相关疑难解决方法(0)

如何模拟反应自定义钩子返回值?

这是我的自定义钩子:

  export function useClientRect() {
    const [scrollH, setScrollH] = useState(0);
    const [clientH, setClientH] = useState(0);
    const ref = useCallback(node => {
      if (node !== null) {
        setScrollH(node.scrollHeight);
        setClientH(node.clientHeight);
      }
    }, []);
    return [scrollH, clientH, ref];
  }
}
Run Code Online (Sandbox Code Playgroud)

我希望每次调用它时,它都会返回我的值。喜欢:

jest.mock('useClientRect', () => [300, 200, () => {}]);
Run Code Online (Sandbox Code Playgroud)

我怎样才能做到这一点?

reactjs jestjs react-testing-library react-hooks

28
推荐指数
3
解决办法
3万
查看次数

使用jsdom获取DOM元素的实际宽度

我想知道我是否可以获得DOM元素的实际宽度和坐标,因为我可以在浏览器中使用.clientWidth/.offsetWidth.

jsdom是否具有浏览器渲染功能以获取此数据?

如果没有,我怎么能在node.js服务器中得到它?

谢谢!

node.js jsdom

7
推荐指数
1
解决办法
4746
查看次数

如何使用 jest.mock 和 React 测试库来模拟 useRef

我有一个测试用例,我需要模拟 useRef 才能返回模拟当前值。我尝试了 jest.mock 但它返回一个 HTMLDivElement 。

代码:

   const ref = useRef<HTMLDivElement | null>(null);
Run Code Online (Sandbox Code Playgroud)

测试:

  jest.mock('react', () => {
     const originReact = jest.requireActual('react');
       return {
          ...originReact,
          useRef: jest.fn(),
       };
  });



  React.useRef.mockReturnValue({ current: {offsetWith: 100} }); 
Run Code Online (Sandbox Code Playgroud)

模拟回报

[ { type: 'return', value: { current: [HTMLDivElement] } } ]
Run Code Online (Sandbox Code Playgroud)

unit-testing reactjs jestjs react-testing-library react-hooks

5
推荐指数
1
解决办法
2万
查看次数

如何使用react-testing-library使用ref测试逻辑并更新useEffect/useLayoutEffect内的状态

我的组件用于useLayoutEffect执行一个函数来计算位置的两个状态变量。相同的函数被传递给内部容器之一的 Element.scroll 事件:

代码如下所示:

export const Component = ({children}) => {
    // .....

    const containerRef = useRef<HTMLDivElement>(null);
    const [canClickLeft, setCanClickLeft] = useState(false);
    const [canClickRight, setCanClickRight] = useState(false);

    const checkForPosition = () => {
      if (containerRef.current) {
        // logic here;

        const positionLeft = false;
        const positionRight = true;
  
        setCanClickLeft(positionLeft);
        setCanClickRight(positionRight);
      }
    };

    const doSomething = () = {....}
  
    useLayoutEffect(() => {
        checkForPosition();
    });


    return (
      <>
        <StyledContainer onScroll={() => checkForPosition()}>
          {children}
        </StyledContainer>
  
        <button disabled={!canClickLeft} onClick={doSomething}>Click Left</button>
        <button disabled={!canClickRight onClick={doSomething}}>Click …
Run Code Online (Sandbox Code Playgroud)

reactjs react-testing-library react-hooks

2
推荐指数
1
解决办法
3933
查看次数