-
Notifications
You must be signed in to change notification settings - Fork 1
/
Search.test.js
91 lines (78 loc) · 2.27 KB
/
Search.test.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import Search from './Search';
/**
* Create a KeyboardEvent for typing a character.
*
* @todo This is maintained from the previous event setup because typing with
* user.keyboard is taking so long the tests error out.
*
* @param {string} character The character to type.
* @return {KeyboardEvent}
*/
function typeCharacter(character) {
return new KeyboardEvent(
'keydown',
{ key: character, bubbles: true }
);
}
// Set up our document body
document.body.innerHTML = `
<ul>
<li>Anchorage</li>
<li>Baltimore</li>
<li>Chicago</li>
<li>Dallas</li>
<li>El Paso</li>
<li>Fort Lauderdale</li>
<li>Grand Rapids</li>
<li>Hartford</li>
<li>Idaho Falls</li>
</ul>
`;
const listItems = document.querySelectorAll('li');
const list = document.querySelector('ul');
jest.useFakeTimers();
describe('Find the search string', () => {
test.each([
['NodeList', listItems],
['Array of list items', Array.from(listItems)],
['HTML UL Element', list],
])(
'Search for typed string within: %s',
(name, input) => {
const search = new Search(input);
let found = null;
document.addEventListener('keydown', (event) => {
found = search.getItem(event.key);
});
// Typing 'El Paso'
document.dispatchEvent(typeCharacter('e'));
document.dispatchEvent(typeCharacter('l'));
expect(found).toEqual(list.children[4]);
// Advance the timer to clear the search string.
jest.advanceTimersByTime(500);
expect(search.clearSearch).toBeNull();
expect(search.searchString).toEqual('');
// Typing 'Hartford'
document.dispatchEvent(typeCharacter('h'));
document.dispatchEvent(typeCharacter('a'));
expect(found).toEqual(list.children[7]);
}
);
test.each([
['Single list item', list.children[4]],
['Null', document.querySelector('.fake-classname')],
])(
'Should fail with bad input: %s',
(name, input) => {
const search = new Search(input);
let found = null;
document.addEventListener('keydown', (event) => {
found = search.getItem(event.key);
});
// Typing 'El Paso'
document.dispatchEvent(typeCharacter('e'));
document.dispatchEvent(typeCharacter('l'));
expect(found).toBeNull();
}
);
});