Skip to content

Commit

Permalink
fix(events): bind emitters with for..in. (#3059)
Browse files Browse the repository at this point in the history
Fixes #3057
  • Loading branch information
johnjbarton authored Jun 20, 2018
1 parent ab3c0e3 commit b99f03f
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 7 deletions.
5 changes: 3 additions & 2 deletions lib/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,14 @@ function bufferEvents (emitter, eventsToBuffer) {

class KarmaEventEmitter extends EventEmitter {
bind (object) {
Object.keys(object).forEach((method) => {
for (const method in object) {
if (method.startsWith('on') && helper.isFunction(object[method])) {
this.on(helper.camelToSnake(method.substr(2)), function () {
// We do not use an arrow function here, to supply the caller as this.
object[method].apply(object, Array.from(arguments).concat(this))
})
}
})
}
}

emitAsync (name) {
Expand Down
24 changes: 19 additions & 5 deletions test/unit/events.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,34 +20,48 @@ describe('events', () => {
var object = null

beforeEach(() => {
object = sinon.stub({
// Note: es6 class instances have non-enumerable prototype properties.
function FB () {};
FB.prototype = {
onPrototypeBar () {}
}
object = new FB()
Object.assign(object, {
onFoo: () => {},
onFooBar: () => {},
foo: () => {},
bar: () => {}
foo: () => {}
})

emitter.bind(object)
})

it('should register all "on" methods to events', () => {
sinon.spy(object, 'onFoo')
emitter.emit('foo')
expect(object.onFoo).to.have.been.called

sinon.spy(object, 'onFooBar')
emitter.emit('foo_bar')
expect(object.onFooBar).to.have.been.called

sinon.spy(object, 'onPrototypeBar')
emitter.emit('prototype_bar')
expect(object.onPrototypeBar).to.have.been.called

sinon.spy(object, 'foo')
expect(object.foo).not.to.have.been.called
expect(object.bar).not.to.have.been.called
})

it('should bind methods to the owner object', () => {
sinon.spy(object, 'foo')
sinon.spy(object, 'onFoo')
sinon.spy(object, 'onFooBar')
emitter.emit('foo')
emitter.emit('foo_bar')

expect(object.onFoo).to.have.always.been.calledOn(object)
expect(object.onFooBar).to.have.always.been.calledOn(object)
expect(object.foo).not.to.have.been.called
expect(object.bar).not.to.have.been.called
})
})

Expand Down

0 comments on commit b99f03f

Please sign in to comment.