温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Jest测试React Hooks的useLayoutEffect

发布时间:2024-08-27 21:09:37 来源:亿速云 阅读:79 作者:小樊 栏目:编程语言

useLayoutEffect 是 React Hooks 中的一个钩子,它与 useEffect 类似,但在 DOM 更新之后同步执行

首先,创建一个简单的组件,使用 useLayoutEffect

// MyComponent.js
import React, { useLayoutEffect, useState } from 'react';

const MyComponent = () => {
  const [width, setWidth] = useState(window.innerWidth);

  useLayoutEffect(() => {
    const handleResize = () => {
      setWidth(window.innerWidth);
    };

    window.addEventListener('resize', handleResize);

    return () => {
      window.removeEventListener('resize', handleResize);
    };
  }, []);

  return <div>Window width: {width}</div>;
};

export default MyComponent;

接下来,使用 Jest 和 @testing-library/react 对此组件进行测试:

// MyComponent.test.js
import React from 'react';
import { render, unmountComponentAtNode } from '@testing-library/react';
import MyComponent from './MyComponent';

let container = null;

beforeEach(() => {
  container = document.createElement('div');
  document.body.appendChild(container);
});

afterEach(() => {
  unmountComponentAtNode(container);
  container.remove();
  container = null;
});

describe('MyComponent', () => {
  test('updates window width on resize', () => {
    const originalWidth = window.innerWidth;
    const newWidth = originalWidth + 100;

    // Render the component
    render(<MyComponent />, container);

    // Expect initial width
    expect(container.textContent).toBe(`Window width: ${originalWidth}`);

    // Change window width and trigger resize event
    Object.defineProperty(window, 'innerWidth', { value: newWidth });
    window.dispatchEvent(new Event('resize'));

    // Expect updated width
    expect(container.textContent).toBe(`Window width: ${newWidth}`);
  });
});

这个测试用例首先检查组件初始化时的窗口宽度。然后,我们通过更改 window.innerWidth 并触发 resize 事件来模拟窗口大小调整。最后,我们期望组件能够正确地更新宽度。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI