-
Notifications
You must be signed in to change notification settings - Fork 0
/
test.js
88 lines (78 loc) · 2.59 KB
/
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
const test = require('tape')
const NodeEventHandler = require('./')
const existy = require('existy')
const EventEmitter = require('events')
test('can insatiate and has required API methods', t => {
class HandlerClass {
oncustomevent (ev) {
console.log(ev)
}
}
const ctx = new HandlerClass()
const handler = new NodeEventHandler(ctx)
t.equal(typeof handler.addEventListeners, 'function', 'addEventListeners is defined')
t.equal(typeof handler.removeEventListeners, 'function', 'removeEventListeners is defined')
t.equal(typeof handler.handleEvent, 'function', 'handleEvent is defined')
t.true(Array.isArray(handler.events), 'events getter returns an array')
t.equal(handler.events.length, 1, 'events getter has one event')
t.throws(() => {
const handler = new NodeEventHandler()
console.log(handler.events)
}, /context is required/, 'missing context throws')
t.end()
})
test('works even without handlers', t => {
class HandlerClass {}
const ctx = new HandlerClass()
const handler = new NodeEventHandler(ctx)
t.true(Array.isArray(handler.events), 'events getter returns an array')
t.equal(handler.events.length, 0, 'events getter has 0 events')
t.end()
})
test('handles events when instantiated with a node', t => {
const ee = new EventEmitter()
class HandlerClass {
constructor () {
this.foo = 'bar'
}
oncustomevent (ev) {
t.equal(ev.detail.unicorn, 'rainbows', 'handled event')
t.equal(this.foo, 'bar', 'bound properties are accessible')
t.end()
}
}
const ctx = new HandlerClass()
const handler = new NodeEventHandler(ctx, ee)
t.true(existy(handler), 'handler created')
ee.emit('customevent', { detail: { unicorn: 'rainbows' } })
})
test('handles events when attached after the fact', t => {
const ee = new EventEmitter()
class HandlerClass {
oncustomevent (ev) {
t.equal(ev.detail.unicorn, 'rainbows', 'handled event')
t.end()
}
}
const ctx = new HandlerClass()
const handler = new NodeEventHandler(ctx)
handler.addEventListeners(ee)
ee.emit('customevent', { detail: { unicorn: 'rainbows' } })
})
test('doesnt handle events when removed', t => {
const ee = new EventEmitter()
class HandlerClass {
oncustomevent (ev) {
t.fail('this shouldnt run')
}
}
const ctx = new HandlerClass()
const handler = new NodeEventHandler(ctx, ee)
t.true(existy(handler), 'handler created')
handler.removeEventListeners(ee)
ee.emit('customevent', { detail: { unicorn: 'rainbows' } })
setTimeout(() => {
t.ok(true, 'event handler doesnt catch anything')
t.end(null)
}, 5)
})