Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MeteorJS: How to stub validated method in unit test

I am using validated methods (mdg:validated-method) with LoggedInMixin (tunifight:loggedin-mixin).

Now I have a problem with my unit tests, as they fail with notLogged error, because in the unit tests there is no logged user of course. How do I have to stub that?

method

const resetEdit = new ValidatedMethod({
  name: 'reset',
  mixins: [LoggedInMixin],
  checkLoggedInError: { error: 'notLogged' }, // <- throws error if user is not logged in
  validate: null,

  run ({ id }) {
    // ...
  }
})

unit test

describe('resetEdit', () => {
  it('should reset data', (done) => {
    resetEdit.call({ id: 'IDString' })
  })
})

Unit tests throws Error: [notLogged].

like image 877
user3142695 Avatar asked Sep 28 '17 23:09

user3142695


1 Answers

Edit:

validated-method has a built-in way of providing a context and it is documented in the README, exactly for cases like the one in your question.

method#_execute(context: Object, args: Object)

Call this from your test code to simulate calling a method on behalf of a particular user:

(source)

  it('should reset data', (done) => {
      resetEdit._execute({userId: '123'}, { id: 'IDString' });
      done();
  });

Original answer:

I believe that this can be achieved using the DDP._CurrentMethodInvocation meteor environment variable.

If you run the test in a scope where the its value is an object a userId string, it will be merged with the rest of the method invocation context object and the mixin will not fail.

describe('resetEdit', () => {
  it('should reset data', (done) => {
    DDP._CurrentMethodInvocation.withValue({userId: '123'}, function() {
      console.log(DDP._CurrentInvocation.get()); // {userId: '123'}
      resetEdit.call({ id: 'IDString' });
      done();
    })
  });
})
like image 84
MasterAM Avatar answered Sep 23 '22 15:09

MasterAM