dev-resources.site
for different kinds of informations.
How to test whether a specific button is included in the document
Published at
8/12/2021
Categories
testinglibrary
jest
jestdom
Author
cuimingda
Author
9 person written this
cuimingda
open
最简单的方式的,其实是用test ID,没有任何限制,因为这个ID是我们指定用来测试的,所以跟业务没有什么关系,也不需要考虑按钮显示文字发生变化。
测试用例,主要要用queryByTestId
,而不是getByTestId
,如果用了后者,没有找到这个元素的时候会抛出异常。
it('should have increase button', () => {
const { queryByTestId } = render(<App />);
const button = queryByTestId('increase-button');
expect(button).toBeInTheDocument();
})
通过验证的代码
<button data-testid="increase-button">+1</button>
另外一种方式,可以用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();
})
通过验证的代码
<button aria-label="increase-button">+1</button>
如果我们要进一步验证,可以测试查询到元素的类型和内容
expect(button.nodeName).toBe('BUTTON');
expect(button.textContent).toBe('+1');
References
testinglibrary Article's
18 articles in total
Integration Testing in React: Best Practices with Testing Library
read article
Unit Tests for Frontend Developers [Part 2]
read article
Testes unitários em React com Jest e testing library
read article
Unit tests in React with Jest and Testing Library
read article
Setup Jest, Babel e testing library para testes unitários em React
read article
Setup Jest, Babel and testing library for unit testing in React
read article
How To Setup Cypress Testing Library? A Smarter Way To Select Elements.
read article
Testing Library - Queries
read article
Configurando o Jest e Testing Library no Vite
read article
Getting Started with Redux and Testing Library
read article
How to test whether a specific button is included in the document
currently reading
Test Driven Development with Svelte - Querying Elements
read article
How to query element by className in Testing Library
read article
How to simulate clicking a button in Testing Library
read article
Test Driven Development with Svelte - Setup
read article
Testes em React Native com Jest e Testing Library, Configurando o ambiente
read article
Modern ways of UI end to end testing with Cypress
read article
Making sure you're using the correct query
read article
Featured ones: