Jest测试React Hooks的useRef

发布时间:2024-08-27 20:29:37 作者:小樊
来源:亿速云 阅读:82

jest@testing-library/react 是两个常用的库,用于测试 React 组件

  1. 首先,确保已安装所需的依赖项:
npm install --save-dev jest @testing-library/react @testing-library/jest-dom
  1. 创建一个名为 MyComponent.js 的文件,其中包含使用 useRef 的 React 组件:
import React, { useRef } from 'react';

const MyComponent = () => {
  const inputRef = useRef(null);

  const handleClick = () => {
    inputRef.current.focus();
  };

  return (
    <div>
     <input ref={inputRef} type="text" />
     <button onClick={handleClick}>Focus input</button>
    </div>
  );
};

export default MyComponent;
  1. 在同一目录下创建一个名为 MyComponent.test.js 的文件,编写针对 MyComponent 的测试用例:
import React from 'react';
import { render, fireEvent, screen } from '@testing-library/react';
import '@testing-library/jest-dom/extend-expect';
import MyComponent from './MyComponent';

describe('MyComponent', () => {
  it('should focus the input field when the button is clicked', () => {
    render(<MyComponent />);

    const input = screen.getByRole('textbox');
    const button = screen.getByText('Focus input');

    expect(input).not.toHaveFocus();

    fireEvent.click(button);

    expect(input).toHaveFocus();
  });
});
  1. package.json 中添加测试脚本:
{
  "scripts": {
    "test": "jest"
  }
}
  1. 最后,运行测试:
npm test

这将运行 MyComponent 的测试用例,并检查点击按钮后输入框是否获得焦点。如果一切正常,您应该会看到类似于以下的测试结果:

PASS  ./MyComponent.test.js
  MyComponent
    ✓ should focus the input field when the button is clicked (28 ms)
推荐阅读:
  1. 怎么在React中使用Hooks
  2. React Hooks在React-refresh模块热替换下的异常行为怎么解决

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

jest

上一篇:Jest框架中的测试重命名策略

下一篇:Jest与Jest测试配置最佳实践

相关阅读

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

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