Mocking Meteor.userId() for Jasmine server unit

Is there a way to mock up Meteor.userId() for a Jasmine server unit test? I am trying to do this so I can run code like the following in my server methods:

if (! Meteor.userId()) {
throw new Meteor.Error(‘not-authorized’);
}

Thanks!

Yes. Just use spyOn: spyOn(Meteor, 'userId').and.returnValue('123456') (Docs)

Thanks much @Sanjo! Worked great :slight_smile:

Would there be a version that works with Mocha/Sinon? If I do Meteor.userId = sinon.stub().returns('42') it will always return 42 later on. But I would want it to reset to the default behaviour after. (with as little code as possible)

Found it. Will add it to my boilerplate soon.

import sinon from 'sinon'
import { Meteor } from 'meteor/meteor'

describe('...', function() {
  beforeEach(function () {
    sandbox = sinon.sandbox.create()
  })

  afterEach(function () {
    sandbox.restore()
  })

  it('should go to the sign-in state', function () {
    mockTemplate('imports/ui/states/sign-in/main.html')
    goTo('')
    chai.expect($state.current.name).to.equal('sign-in')
  })

  it('should go to the home state when user is logged in', function () {
    sandbox.stub(Meteor, 'userId').returns('42')
    mockTemplate('imports/ui/states/home/main.html')
    goTo('')
    chai.expect($state.current.name).to.equal('home')
  })

  it('should go to the sign-in state again', function () {
    mockTemplate('imports/ui/states/sign-in/main.html')
    goTo('')
    chai.expect($state.current.name).to.equal('sign-in')
  })

})
1 Like

Hey trajano-

Did you ever get your userId stub to work in a Meteor.method? It seems that Meteor resets my stub for Meteor.userId to null before invoking the Meteor method, thus halting my unit test on:

if(!this.userId){
throw new Meteor.Error(“not-logged-in”, “You’re not logged-in!!”);
}

It’s in a different scope, so I’m not sure how to get it to stub in the Meteor.method without modifying the source code.

No I had to do a Meteor.isTest() call

1 Like