Skip to content

Commit f783e76

Browse files
committed
Add test cases
1 parent 625ba21 commit f783e76

File tree

3 files changed

+74
-5
lines changed

3 files changed

+74
-5
lines changed

dist/index.js

+2-1
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

src/index.js

+7
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,13 @@ const keypress = key => {
2121
}
2222

2323
class TypeTrigger {
24+
// This is mainly used for testing, but could be useful in application code as well
25+
static type (word) {
26+
word.split('').forEach(character => {
27+
keypress(character)
28+
})
29+
}
30+
2431
static register (word, cb) {
2532
if (!isInitialized) {
2633
window.document.addEventListener('keypress', e => { keypress(e.key) })

test/index.test.js

+65-4
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,72 @@
11
import TypeTrigger from '../dist/index.js'
22

3-
test('One', () => {
3+
test('It triggers a single event when the word is typed', () => {
44
let a = false
55

6-
TypeTrigger.register('monkey', () => {
7-
a = true
8-
})
6+
TypeTrigger.register('monkey', () => { a = true })
97

8+
expect(a).toBe(false)
9+
TypeTrigger.type('monkey')
10+
expect(a).toBe(true)
11+
})
12+
13+
test('It resets correctly when mistyping', () => {
14+
let a = false
15+
16+
TypeTrigger.register('monkey', () => { a = true })
17+
18+
TypeTrigger.type('monke')
19+
expect(a).toBe(false)
20+
21+
TypeTrigger.type('onkey')
22+
expect(a).toBe(false)
23+
24+
TypeTrigger.type('mon')
25+
TypeTrigger.type('ke')
26+
expect(a).toBe(false)
27+
TypeTrigger.type('y')
28+
expect(a).toBe(true)
29+
})
30+
31+
test('It can handle multiple registrations', () => {
32+
let a = false
33+
let b = false
34+
35+
TypeTrigger.register('monkey', () => { a = true })
36+
TypeTrigger.register('donkey', () => { b = true })
37+
38+
TypeTrigger.type('monk')
39+
TypeTrigger.type('donk')
40+
TypeTrigger.type('key')
41+
expect(a).toBe(false)
42+
expect(b).toBe(false)
43+
44+
TypeTrigger.type('mon')
45+
TypeTrigger.type('don')
46+
TypeTrigger.type('key')
47+
expect(a).toBe(false)
48+
expect(b).toBe(true)
49+
})
50+
51+
test('The same word can be registered multiple times', () => {
52+
let counter = 0
53+
54+
TypeTrigger.register('monkey', () => { counter++ })
55+
TypeTrigger.register('monkey', () => { counter++ })
56+
TypeTrigger.register('donkey', () => { counter++ })
57+
58+
TypeTrigger.type('donkey')
59+
expect(counter).toBe(1)
60+
61+
TypeTrigger.type('monkey')
62+
expect(counter).toBe(3)
63+
})
64+
65+
test('Invalid registrations does not throw an error', () => {
66+
let counter = 0
67+
68+
TypeTrigger.register('monkey', 'not-a-function')
1069

70+
TypeTrigger.type('monkey')
71+
expect(counter).toBe(0)
1172
})

0 commit comments

Comments
 (0)