Testing for thrown Meteor.Error


#1

I am doing to ToDo tutorial and on the section for testing (https://www.meteor.com/tutorials/blaze/testing). I wanted to write a test for a failed insert when the user is not logged in. Specifically method is:

'tasks.insert' (text) {
    check (text, String);
    
    // Make sure the user is logged in before inserting the task
    if (! this.userId) {
      throw new Meteor.Error ('not-authorized');
    }
    
    Tasks.insert ({
      text,
      createdAt: new Date (),
      owner: this.userId,
      username: Meteor.users.findOne (this.userId).username,
    });
  },

From what I read elsewhere, you need to wrap the function being called in an anonymous function as I want to pass arguments. So my test is:

const badInsert = function (){
          Tasks.insert ({
            text: 'test task',
            createAt: new Date (),
            owner: null,
            username: '',
          });
        };
        
assert.throws (badInsert, Meteor.Error, 'not-authorized');

When I run this test, however, I get:

Error: expected [Function: badInsert] to throw Error

I have also tried an assert on “Error” instead of “Meteor.Error” and get the same result. I read another thread where it implied that because Meteor.Error is a special type of error for passing from the server to the client that something happened it might not be a “normal” error.

I did successfully write a test that showed no task was inserted.

assert.equal (Tasks.find ().count (), 0);

My basic question is: how to I test for this type of thrown error?

Thanks in advance,

Dale


#2

How about

it(‘cant add a video with out a userId’, () => {
const insertTask = Meteor.server.method_handlers[‘videos.insert’];
// Set up a fake method invocation that looks like what the method expects.
// no user id
const invocation = {};
assert.throws(() => {
insertTask.apply(invocation, [‘test-video-object-goes-here’]);
}, Meteor.Error, ‘[not-authorized]’);
});