DEV Community

Cui Mingda
Cui Mingda

Posted on

How to test whether a specific button is included in the document

最简单的方式的,其实是用test ID,没有任何限制,因为这个ID是我们指定用来测试的,所以跟业务没有什么关系,也不需要考虑按钮显示文字发生变化。

测试用例,主要要用queryByTestId,而不是getByTestId,如果用了后者,没有找到这个元素的时候会抛出异常。

it('should have increase button', () => {
  const { queryByTestId } = render(<App />);
  const button = queryByTestId('increase-button');
  expect(button).toBeInTheDocument();
})
Enter fullscreen mode Exit fullscreen mode

通过验证的代码

<button data-testid="increase-button">+1</button>
Enter fullscreen mode Exit fullscreen mode

另外一种方式,可以用queryByRole,对于button元素来说,不需要显性设置,他的role就是button,这时候可能还需要搭配其他的属性,比如我们用aria-label

it('should have increase button', () => {
  const { queryByRole } = render(<App />);
  const button = queryByRole('button', { name: 'increase-button' });
  expect(button).toBeInTheDocument();
})
Enter fullscreen mode Exit fullscreen mode

通过验证的代码

<button aria-label="increase-button">+1</button>
Enter fullscreen mode Exit fullscreen mode

如果我们要进一步验证,可以测试查询到元素的类型和内容

expect(button.nodeName).toBe('BUTTON');
expect(button.textContent).toBe('+1');
Enter fullscreen mode Exit fullscreen mode

References

Top comments (0)