javascript - meteor JS : How to stub validated method in unit test

标签 javascript unit-testing meteor stub

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

现在我的单元测试出现了问题,因为它们因 notLogged 错误而失败,因为在单元测试中当然没有登录用户。 我怎么必须 stub 呢?

方法

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' })
  })
})

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

最佳答案

编辑:

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

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

原答案:

我相信这可以使用 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();
    })
  });
})

关于javascript - meteor JS : How to stub validated method in unit test,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46479562/

相关文章:

javascript - meteor 测试 : Mocha doesn't find all test files

javascript - meteor :如何按关注最多的用户排序?

javascript - 面向对象的 meteor

javascript - 无法将 id 保存到变量

javascript - 在asp.net中加载div而不刷新页面

javascript - 单击 html 按钮发送电子邮件

php - 我在哪里可以找到 Simpletest 的扩展 HTML 报告程序?

c# - 我应该如何在 C# 中对多个必填字段进行单元测试?

meteor - 将 Meteor.js 中的模块与 Typescript 一起使用

javascript - ng-repeat 中的 ng-model 失去焦点