Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(events): bind emitters with for..in. #3059

Merged
merged 1 commit into from
Jun 20, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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