EventEmitterTests.js 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import { expect } from 'chai'
  2. import sinon from 'sinon'
  3. import EventEmitter from '@/utils/EventEmitter'
  4. describe('EventEmitter', function () {
  5. beforeEach(function () {
  6. this.eventEmitter = new EventEmitter()
  7. })
  8. it('calls listeners', function () {
  9. const cb1 = sinon.stub()
  10. const cb2 = sinon.stub()
  11. this.eventEmitter.on('foo', cb1)
  12. this.eventEmitter.on('bar', cb2)
  13. this.eventEmitter.trigger('foo')
  14. expect(cb1).to.have.been.called
  15. expect(cb2).to.not.have.been.called
  16. })
  17. it('calls multiple listeners', function () {
  18. const cb1 = sinon.stub()
  19. const cb2 = sinon.stub()
  20. this.eventEmitter.on('foo', cb1)
  21. this.eventEmitter.on('foo', cb2)
  22. this.eventEmitter.trigger('foo')
  23. expect(cb1).to.have.been.called
  24. expect(cb2).to.have.been.called
  25. })
  26. it('calls listeners with namespace', function () {
  27. const cb1 = sinon.stub()
  28. const cb2 = sinon.stub()
  29. this.eventEmitter.on('foo', cb1)
  30. this.eventEmitter.on('foo.bar', cb2)
  31. this.eventEmitter.trigger('foo')
  32. expect(cb1).to.have.been.called
  33. expect(cb2).to.have.been.called
  34. })
  35. it('removes listeners', function () {
  36. const cb = sinon.stub()
  37. this.eventEmitter.on('foo', cb)
  38. this.eventEmitter.off('foo')
  39. this.eventEmitter.trigger('foo')
  40. expect(cb).to.not.have.been.called
  41. })
  42. it('removes namespaced listeners', function () {
  43. const cb = sinon.stub()
  44. this.eventEmitter.on('foo.bar', cb)
  45. this.eventEmitter.off('foo.bar')
  46. this.eventEmitter.trigger('foo')
  47. expect(cb).to.not.have.been.called
  48. })
  49. it('does not remove unnamespaced listeners if off called with namespace', function () {
  50. const cb1 = sinon.stub()
  51. const cb2 = sinon.stub()
  52. this.eventEmitter.on('foo', cb1)
  53. this.eventEmitter.on('foo.bar', cb2)
  54. this.eventEmitter.off('foo.bar')
  55. this.eventEmitter.trigger('foo')
  56. expect(cb1).to.have.been.called
  57. expect(cb2).to.not.have.been.called
  58. })
  59. })