-
Notifications
You must be signed in to change notification settings - Fork 472
/
Copy pathexample.js
54 lines (48 loc) · 1.9 KB
/
example.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
// query utilities:
import {getByLabelText, getByText, getByTestId, queryByTestId, wait} from '../'
// adds special assertions like toHaveTextContent
import '../extend-expect'
function getExampleDOM() {
// This is just a raw example of setting up some DOM
// that we can interact with. Swap this with your UI
// framework of choice 😉
const div = document.createElement('div')
div.innerHTML = `
<label for="username">Username</label>
<input id="username" />
<button>Print Username</button>
`
const button = div.querySelector('button')
const input = div.querySelector('input')
button.addEventListener('click', () => {
// let's pretend this is making a server request, so it's async
// (you'd want to mock this imaginary request in your unit tests)...
setTimeout(() => {
const printedUsernameContainer = document.createElement('div')
printedUsernameContainer.innerHTML = `
<div data-testid="printed-username">${input.value}</div>
`
div.appendChild(printedUsernameContainer)
}, Math.floor(Math.random() * 200))
})
return div
}
test('examples of some things', async () => {
const famousWomanInHistory = 'Ada Lovelace'
const container = getExampleDOM()
// Get form elements by their label text.
// An error will be thrown if one cannot be found (accessibility FTW!)
const input = getByLabelText(container, 'Username')
input.value = famousWomanInHistory
// Get elements by their text, just like a real user does.
getByText(container, 'Print Username').click()
await wait(() =>
expect(queryByTestId(container, 'printed-username')).toBeInTheDOM(),
)
// getByTestId and queryByTestId are an escape hatch to get elements
// by a test id (could also attempt to get this element by it's text)
expect(getByTestId(container, 'printed-username')).toHaveTextContent(
famousWomanInHistory,
)
expect(container).toMatchSnapshot()
})