2

I'm trying to test my insert function but It fail with UserAccount: Error: Cannot read property 'username' of undefined

I don't know how to make the test pass for inserting a post, here is my method:

Meteor.methods({

  'posts.insert'(title, content) {
     check(title, String);
     check(content, String);


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

     const urlSlug = getSlug(title);

     Posts.insert({
        title,
        content,
        urlSlug,
        createdAt: new Date(),
        owner: this.userId,
        username: Meteor.users.findOne(this.userId).username,
     });
  },

});

And here is the test method I'm trying to test:

if (Meteor.isServer) {
    describe('Posts', () => {
        describe('methods', () => {
            const userId = Random.id();
            let postId;

            beforeEach(() => {
                Posts.remove({});

                postId = Posts.insert({
                    title: 'test post',
                    content: 'test content',
                    urlSlug: 'test-post',
                    createdAt: new Date(),
                    owner: userId,
                    username: 'toto',
                });
            });

            // TEST INSERT METHOD
            it('can insert post', () => {
                const title = "test blog 2";
                const content = "test content blog 2";

                const insertPost Meteor.server.method_handlers['posts.insert'];
                const invocation = { userId };
                insertPost.apply(invocation, [title, content]);
                assert.equal(Posts.find().count(), 2);
            });
       });
   });
 }

Could you help me please ?

myput
  • 422
  • 1
  • 10
  • 26

1 Answers1

0

How about using sinon to stub the meteor call? Although I'm not sure if it works with nested object (if someone can confirm).

sinon.stub(Meteor, 'users.findOne').returns({ username: 'Foo' });

And don't forget to restore it after you have used it (in afterEach() for example).

Meteor.users.findOne.restore();
Max G.
  • 266
  • 1
  • 6
  • `sinon.stub(Meteor.users, 'findOne').returns({ username: 'Foo' });` is the correct way. I tried above and got some problem about that not being a property. – Kyle Parisi Jan 28 '17 at 17:37