rsnext/test/unit/mitt.unit.test.js

84 lines
1.6 KiB
JavaScript
Raw Normal View History

/* eslint-env jest */
import mitt from 'next/dist/next-server/lib/mitt'
2017-07-09 05:46:53 +02:00
describe('mitt', () => {
2017-07-09 05:46:53 +02:00
describe('With listeners', () => {
2020-05-18 19:16:07 +02:00
it('should listen to a event', () => {
2020-05-18 21:24:37 +02:00
return new Promise((resolve) => {
2020-05-18 19:16:07 +02:00
const ev = mitt()
ev.on('sample', resolve)
ev.emit('sample')
})
2017-07-09 05:46:53 +02:00
})
it('should listen to multiple listeners', () => {
const ev = mitt()
2017-07-09 05:46:53 +02:00
let cnt = 0
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', () => {
const ev = mitt()
2017-07-09 05:46:53 +02:00
const data = []
2020-05-18 21:24:37 +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', () => {
const ev = mitt()
2017-07-09 05:46:53 +02:00
let data
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', () => {
const ev = mitt()
2017-07-09 05:46:53 +02:00
let cnt = 0
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', () => {
const ev = mitt()
2017-07-09 05:46:53 +02:00
ev.emit('aaaa', 10, 20)
})
})
})