【问题标题】:MeteorJS: How to stub validated method in unit testMeteorJS:如何在单元测试中存根验证方法
【发布时间】:2017-09-28 23:11:07
【问题描述】:

我正在使用经过验证的方法 (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 吗?您还可以尝试在运行测试之前与用户一起创建夹具,然后在运行测试之前使用该用户登录
  • 我不太确定该怎么做,因为我正在使用 meteor test --once 命令在我的 CI 工作流程中进行单元测试。所以我想我无法登录任何用户...
  • 你可以,在你的测试中你应该能够做类似Meteor.loginWithPassword(user, password, function({ resetEdit.call({id: "IDString"}); }));
  • 你试过resetEdit.call.call({ userId: Random.id() }, { id: 'IDString' })吗?

标签: javascript unit-testing meteor stub


【解决方案1】:

编辑:

validated-method 具有提供上下文的内置方式,它记录在 README 中,完全适用于您问题中的情况。

方法#_execute(上下文:对象,参数:对象)

从您的测试代码中调用它来模拟代表特定用户调用方法:

(source)

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

原答案:

我相信这可以使用DDP._CurrentMethodInvocationmeteor 环境变量来实现。

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

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,而是在运行函数中手动测试登录用户?
  • mixin 没问题。我不确定为什么不能直接使用run,但我确实找到了一种更简单的方法来实现在合成上下文中运行。我将更新我的答案以包含它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-04-25
  • 1970-01-01
  • 2019-02-06
  • 2015-05-31
  • 2020-05-25
  • 1970-01-01
  • 2011-06-20
相关资源
最近更新 更多