|
| 1 | +--- |
| 2 | +id: ecosystem-testing-library-selector |
| 3 | +title: testing-library-selector |
| 4 | +--- |
| 5 | + |
| 6 | +[`testing-library-selector`][gh] is a library for `@testing-library` that |
| 7 | +provides reusable selectors. Written in typescript. |
| 8 | + |
| 9 | +``` |
| 10 | +npm install --save-dev testing-library-selector |
| 11 | +``` |
| 12 | + |
| 13 | +```typescript |
| 14 | +import { byLabelText, byRole, byTestId } from './selector' |
| 15 | + |
| 16 | +// define reusable selectors |
| 17 | +const ui = { |
| 18 | + container: byTestId('my-container'), |
| 19 | + submitButton: byRole('button', { name: 'Submit' }), |
| 20 | + usernameInput: byLabelText('Username:'), |
| 21 | + |
| 22 | + // can encode more specific html element type |
| 23 | + passwordInput: byLabelText<HTMLInputElement>('Password:'), |
| 24 | +} |
| 25 | + |
| 26 | +// reuse them in the same test or across multiple tests by calling |
| 27 | +// .get(), .getAll(), .find(), .findAll(), .query(), .queryAll() |
| 28 | +it('example test', async () => { |
| 29 | + // by default elements will be queried against screen |
| 30 | + await ui.submitButton.find() |
| 31 | + expect(ui.submitButton.query()).not.toBeInDocument() |
| 32 | + expect(ui.submitButton.get()).toBeInDocument() |
| 33 | + |
| 34 | + const containers = ui.container.getAll() |
| 35 | + expect(containers).toHaveLength(3) |
| 36 | + |
| 37 | + // provide a container as first param to query element inside that container |
| 38 | + const username = ui.usernameInput.get(containers[0]) |
| 39 | +}) |
| 40 | +``` |
| 41 | + |
| 42 | +- [testing-library-selector on GitHub][gh] |
| 43 | + |
| 44 | +[gh]: https://github.com/domasx2/testing-library-selector |
0 commit comments