2018-10-20 17:00:01 +02:00
|
|
|
/* eslint-env jest */
|
2019-09-04 16:00:54 +02:00
|
|
|
import mitt from 'next/dist/next-server/lib/mitt'
|
2017-07-09 05:46:53 +02:00
|
|
|
|
2019-01-05 12:15:25 +01:00
|
|
|
describe('mitt', () => {
|
2017-07-09 05:46:53 +02:00
|
|
|
describe('With listeners', () => {
|
2019-05-30 03:19:32 +02:00
|
|
|
it('should listen to a event', done => {
|
2019-01-04 21:49:21 +01:00
|
|
|
const ev = mitt()
|
2017-07-09 05:46:53 +02:00
|
|
|
ev.on('sample', done)
|
|
|
|
ev.emit('sample')
|
|
|
|
})
|
|
|
|
|
|
|
|
it('should listen to multiple listeners', () => {
|
2019-01-04 21:49:21 +01:00
|
|
|
const ev = mitt()
|
2017-07-09 05:46:53 +02:00
|
|
|
let cnt = 0
|
|
|
|
|
2019-05-30 03:19:32 +02:00
|
|
|
ev.on('sample', () => {
|
|
|
|
cnt += 1
|
|
|
|
})
|
|
|
|
ev.on('sample', () => {
|
|
|
|
cnt += 1
|
|
|
|
})
|
2017-07-09 05:46:53 +02:00
|
|
|
|
|
|
|
ev.emit('sample')
|
|
|
|
|
|
|
|
expect(cnt).toBe(2)
|
|
|
|
})
|
|
|
|
|
|
|
|
it('should listen to multiple events', () => {
|
2019-01-04 21:49:21 +01:00
|
|
|
const ev = mitt()
|
2017-07-09 05:46:53 +02:00
|
|
|
const data = []
|
2019-05-30 03:19:32 +02:00
|
|
|
const cb = name => {
|
|
|
|
data.push(name)
|
|
|
|
}
|
2017-07-09 05:46:53 +02:00
|
|
|
|
|
|
|
ev.on('sample1', cb)
|
|
|
|
ev.on('sample2', cb)
|
|
|
|
|
|
|
|
ev.emit('sample1', 'one')
|
|
|
|
ev.emit('sample2', 'two')
|
|
|
|
|
|
|
|
expect(data).toEqual(['one', 'two'])
|
|
|
|
})
|
|
|
|
|
|
|
|
it('should support multiple arguments', () => {
|
2019-01-04 21:49:21 +01:00
|
|
|
const ev = mitt()
|
2017-07-09 05:46:53 +02:00
|
|
|
let data
|
|
|
|
|
2019-05-30 03:19:32 +02:00
|
|
|
ev.on('sample', (...args) => {
|
|
|
|
data = args
|
|
|
|
})
|
2017-07-09 05:46:53 +02:00
|
|
|
ev.emit('sample', 'one', 'two')
|
|
|
|
|
|
|
|
expect(data).toEqual(['one', 'two'])
|
|
|
|
})
|
|
|
|
|
|
|
|
it('should possible to stop listening an event', () => {
|
2019-01-04 21:49:21 +01:00
|
|
|
const ev = mitt()
|
2017-07-09 05:46:53 +02:00
|
|
|
let cnt = 0
|
2019-05-30 03:19:32 +02:00
|
|
|
const cb = () => {
|
|
|
|
cnt += 1
|
|
|
|
}
|
2017-07-09 05:46:53 +02:00
|
|
|
|
|
|
|
ev.on('sample', cb)
|
|
|
|
|
|
|
|
ev.emit('sample')
|
|
|
|
expect(cnt).toBe(1)
|
|
|
|
|
|
|
|
ev.off('sample', cb)
|
|
|
|
|
|
|
|
ev.emit('sample')
|
|
|
|
expect(cnt).toBe(1)
|
|
|
|
})
|
|
|
|
})
|
|
|
|
|
|
|
|
describe('Without a listener', () => {
|
|
|
|
it('should not fail to emit', () => {
|
2019-01-04 21:49:21 +01:00
|
|
|
const ev = mitt()
|
2017-07-09 05:46:53 +02:00
|
|
|
ev.emit('aaaa', 10, 20)
|
|
|
|
})
|
|
|
|
})
|
|
|
|
})
|