|
| 1 | +/* global describe, it, expect */ |
| 2 | +import EventEmitter from '../../dist/lib/EventEmitter' |
| 3 | + |
| 4 | +describe('EventEmitter', () => { |
| 5 | + describe('With listeners', () => { |
| 6 | + it('should listen to a event', (done) => { |
| 7 | + const ev = new EventEmitter() |
| 8 | + ev.on('sample', done) |
| 9 | + ev.emit('sample') |
| 10 | + }) |
| 11 | + |
| 12 | + it('should listen to multiple listeners', () => { |
| 13 | + const ev = new EventEmitter() |
| 14 | + let cnt = 0 |
| 15 | + |
| 16 | + ev.on('sample', () => { cnt += 1 }) |
| 17 | + ev.on('sample', () => { cnt += 1 }) |
| 18 | + |
| 19 | + ev.emit('sample') |
| 20 | + |
| 21 | + expect(cnt).toBe(2) |
| 22 | + }) |
| 23 | + |
| 24 | + it('should listen to multiple events', () => { |
| 25 | + const ev = new EventEmitter() |
| 26 | + const data = [] |
| 27 | + const cb = (name) => { data.push(name) } |
| 28 | + |
| 29 | + ev.on('sample1', cb) |
| 30 | + ev.on('sample2', cb) |
| 31 | + |
| 32 | + ev.emit('sample1', 'one') |
| 33 | + ev.emit('sample2', 'two') |
| 34 | + |
| 35 | + expect(data).toEqual(['one', 'two']) |
| 36 | + }) |
| 37 | + |
| 38 | + it('should support multiple arguments', () => { |
| 39 | + const ev = new EventEmitter() |
| 40 | + let data |
| 41 | + |
| 42 | + ev.on('sample', (...args) => { data = args }) |
| 43 | + ev.emit('sample', 'one', 'two') |
| 44 | + |
| 45 | + expect(data).toEqual(['one', 'two']) |
| 46 | + }) |
| 47 | + |
| 48 | + it('should possible to stop listening an event', () => { |
| 49 | + const ev = new EventEmitter() |
| 50 | + let cnt = 0 |
| 51 | + const cb = () => { cnt += 1 } |
| 52 | + |
| 53 | + ev.on('sample', cb) |
| 54 | + |
| 55 | + ev.emit('sample') |
| 56 | + expect(cnt).toBe(1) |
| 57 | + |
| 58 | + ev.off('sample', cb) |
| 59 | + |
| 60 | + ev.emit('sample') |
| 61 | + expect(cnt).toBe(1) |
| 62 | + }) |
| 63 | + |
| 64 | + it('should throw when try to add the same listener multiple times', () => { |
| 65 | + const ev = new EventEmitter() |
| 66 | + const cb = () => {} |
| 67 | + |
| 68 | + ev.on('sample', cb) |
| 69 | + |
| 70 | + const run = () => ev.on('sample', cb) |
| 71 | + |
| 72 | + expect(run).toThrow(/The listener already exising in event: sample/) |
| 73 | + }) |
| 74 | + }) |
| 75 | + |
| 76 | + describe('Without a listener', () => { |
| 77 | + it('should not fail to emit', () => { |
| 78 | + const ev = new EventEmitter() |
| 79 | + ev.emit('aaaa', 10, 20) |
| 80 | + }) |
| 81 | + }) |
| 82 | +}) |
0 commit comments