How to TinyTest meteor.methods?

Hi dears,

I’ve just started reading (and learning) about testing in general, and particularly testing in the meteor land. So, I decided to start trying unit-testing some of my methods, but with no luck. So I’m asking for some help and code examples. Below is the method I’m trying to test followed by the tinytest I’m trying to use.

Meteor.methods({'insertPost': function(text) {


   check(text, String);

   if (!Meteor.userId()) {
      throw new Meteor.Error('not-authorised', 'the user is not logged in at insertPost method');
    // Post content
    text = text.trim();
    if (text.length === 0 || text.length > 2000) {
        throw new Meteor.Error('text-out-of-range', 'text length = 0 or > 2000 at insertPost method');


  // Return postId
  return Posts.insert({createdBy: Meteor.userId(), text: text});


And here is my test:

Tinytest.addAsync('Insert method fails on empty text field?', function(test, next) {

   var text = '    ';'insertPost', text, function(err, res) {

      console.log('err.error: ', err.error);
      console.log('err.reason: ', err.reason);
      console.log('err.details: ', err.details);
      console.log('err.message: ', err.message);
      console.log('err.errorType: ', err.errorType);
      test.isNotUndefined(err, 'err is undefined');
      test.equal(err.error, 'text-out-of-range', 'error different than expected');

So, the problem I’m facing is that the test fails because the user is not logged in. So my question is, how do I stub Meteor.userId() so that the method can pass the non-authorised check and fails where it should, ie, on ‘text-out-of-range’?

Thanks in advance!

You can create a stub for the Meteor.userId function that always returns true, and load it before you run your test. For example, you could load a stubs.js file before your test in your package.js that contains something like:

Meteor.userId = () => {
  return true;

Then when your test runs it will use this overridden function instead.


It worked perfectly!!

Many many thanks for your time @hwillson :grinning: