DEV Community

Dennis Zhang
Dennis Zhang

Posted on • Updated on

jest getByRole 的用法


import { render, screen,fireEvent } from '@testing-library/react';
import MyComponent from './MyComponent';

test('gets the button element', () => {
  render(<MyComponent />);

  // 使用 getByRole 获取 button 元素
  const buttonElement = screen.getByRole('button', { name: /click me/i });

  // 进行断言
  expect(buttonElement).toBeInTheDocument();

  // 使用 getByRole 获取 text input 元素
  const textInputElement = screen.getByRole('textbox', { name: /name/i });

  // 使用 getByRole 获取 number input 元素
  const numberInputElement = screen.getByRole('spinbutton', { name: /age/i });
});
 // 使用 getByRole 获取隐藏的 button 元素
  const hiddenButtonElement = screen.getByRole('button', { name: /hidden button/i, hidden: true });

  fireEvent.change(input, { target: { value: 'Hello, World!' } });

Enter fullscreen mode Exit fullscreen mode

Top comments (0)