MeteorJS:如何在单元测试中存根已验证的方法

7

我正在使用经过验证的方法 (mdg:validated-method) 和 LoggedInMixin (tunifight:loggedin-mixin)。

现在我的单元测试存在问题,因为它们出现了 notLogged 错误,这是因为在单元测试中当然没有已登录的用户。 我该如何进行存根处理?

方法

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

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

单元测试

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

单元测试抛出Error: [notLogged]错误。


你尝试过模拟Meteor.user和Meteor.userId吗?您还可以尝试在运行测试之前创建一个用户夹具,然后使用该用户登录以运行测试。 - Zack Newsham
我不太确定如何做到这一点,因为我正在使用“meteor test --once”命令在我的CI工作流程中进行单元测试。所以我认为我无法登录任何用户... - user3142695
在你的测试中,你应该能够做类似这样的事情:Meteor.loginWithPassword(user, password, function({ resetEdit.call({id: "IDString"}); })); - Zack Newsham
1
你尝试过 resetEdit.call.call({ userId: Random.id() }, { id: 'IDString' }) 吗? - Styx
1个回答

1

编辑:

validated-method 内置了一种提供上下文的方法,并在 README 中进行了记录,正好适用于您问题中的情况。

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

从测试代码中调用此方法,以模拟代表特定用户调用方法:

(source)

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

原始答案:

我相信可以使用DDP._CurrentMethodInvocation Meteor环境变量来实现此目标。

如果您在值为对象且包含userId字符串的范围内运行测试,它将与方法调用上下文对象的其余部分合并,并且混入不会失败。

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();
    })
  });
})

那么您建议不使用那个mixin,而是在run函数中手动测试已登录的用户? - user3142695
Mixin没问题。我不确定为什么run不能直接使用,但我确实找到了一种更简单的方法来使用合成上下文运行。我会更新我的答案以包含它。 - MasterAM

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接