0
# Scoped Queries (within)
1
2
Bind queries to a specific container element for scoped searching when multiple similar elements exist.
3
4
## Within Function
5
6
```typescript
7
function within<QueriesToBind extends Queries = typeof queries>(
8
element: HTMLElement,
9
queriesToBind?: QueriesToBind
10
): BoundFunctions<QueriesToBind>;
11
12
// Alias
13
function getQueriesForElement(...): BoundFunctions;
14
```
15
16
Usage:
17
```javascript
18
import {screen, within} from '@testing-library/dom';
19
20
// Find container
21
const navigation = screen.getByRole('navigation');
22
23
// Query within container
24
const homeLink = within(navigation).getByRole('link', {name: /home/i});
25
const aboutLink = within(navigation).getByRole('link', {name: /about/i});
26
27
// Works with all query variants
28
const form = screen.getByRole('form');
29
const email = within(form).getByLabelText('Email');
30
const password = within(form).getByLabelText('Password');
31
const submitButton = within(form).getByRole('button', {name: /submit/i});
32
```
33
34
## When to Use Within
35
36
**Use when:**
37
- Multiple similar elements in different regions
38
- Need to ensure queries don't match wrong element
39
- Testing nested structures (modals, forms, cards)
40
- Disambiguating multiple instances
41
42
Example - Todo List:
43
```javascript
44
const todoList = screen.getByRole('list');
45
const items = within(todoList).getAllByRole('listitem');
46
47
// Query within first item
48
const firstItem = items[0];
49
const firstCheckbox = within(firstItem).getByRole('checkbox');
50
const firstDelete = within(firstItem).getByRole('button', {name: /delete/i});
51
```
52
53
Example - Modal Dialog:
54
```javascript
55
// Open modal
56
fireEvent.click(screen.getByRole('button', {name: /open/i}));
57
58
// Query within modal only
59
const modal = screen.getByRole('dialog');
60
const closeButton = within(modal).getByRole('button', {name: /close/i});
61
const saveButton = within(modal).getByRole('button', {name: /save/i});
62
```
63
64
## Custom Queries
65
66
Use `within` with custom queries:
67
68
```javascript
69
import {within, buildQueries} from '@testing-library/dom';
70
71
// Define custom query
72
const [
73
queryByDataCy,
74
getAllByDataCy,
75
getByDataCy,
76
findAllByDataCy,
77
findByDataCy,
78
] = buildQueries(
79
(container, id) => container.querySelectorAll(`[data-cy="${id}"]`),
80
(c, id) => `Found multiple with data-cy="${id}"`,
81
(c, id) => `Unable to find with data-cy="${id}"`
82
);
83
84
const customQueries = {
85
queryByDataCy, getAllByDataCy, getByDataCy,
86
findAllByDataCy, findByDataCy
87
};
88
89
// Use with within
90
const container = screen.getByTestId('container');
91
const element = within(container, customQueries).getByDataCy('submit');
92
```
93
94