Unit test of Meteor method with logged in user checking: Meteor.user()

To test a method which deals with logged in user, I use apply method:
For example,
this is the test

    const theMethod = Meteor.server.method_handlers['my.method']
    const thisContext = {
      userId: 'some valid user id here',
    }
    theMethod.apply(thisContext, [{ someParam: 'some value' }])

this is my simple method:

Meteor.methods({
  'my.method'({ someParam }) {
    /*
    * this doesn't work
    * Error: Meteor.userId can only be invoked in method calls or publications.
    */
    // const user = Meteor.user()

    // then I have to do this
    const { userId } = this
    if (!userId) {
      return { status: 'failed', message: 'Please login' }
    }
    const user = Meteor.users.findOne({ _id: userId })
  },
})

The question is: is there other another way to test this kind of method and still use Meteor.user()?
Thank you.

You could (and I think you should) stub out the user, for example using sinon. This is, because a unit test should only test the current unit (function’s) behavior by a well-defined behavior of the external functions it may depend on.

In your example you could therefore stub Meteor.user() to return an id, in case you want to test the behavior, when the id is there and then in another unit the behaviour when it’s not there.

1 Like