Meteor-Community-Packages / meteor-publication-collector

Test a Meteor publication by collecting its output.
https://atmospherejs.com/johanbrook/publication-collector
MIT License
33 stars 20 forks source link

ES6 Error #14

Closed aruntk closed 7 years ago

aruntk commented 7 years ago

this.userId is undefined when using arrow function as argument of the publication.

// pub.js
Meteor.publish('posts', function({ _id }) {
  const user = this.userId; // working correctly
  return Posts.find({ _id, user });
});
// pub.js
Meteor.publish('posts', ({ _id }) => {
  const user = this.userId; // userId is undefined
  return Posts.find({ _id, user });
});
// test.js
const collector = new PublicationCollector({ userId });
collector.collect('posts', (collections) => {
  assert.equal(collections.posts.length, 5);
  done();
});
johanbrook commented 7 years ago

Well, that's the behaviour of arrow functions, no? :) The arrow function's lexical scope in your second example will be bound to the outer, and makes userId be undefined.

robsecord commented 7 years ago

Correct. From MDN:

An arrow function expression [...] does not bind its own this, arguments, super, or new.target.