如何在meteor中进行单元测试,将文档添加到集合中?模拟userId

时间:2016-06-24 23:05:26

标签: unit-testing meteor mocha

感谢您的帮助 -

我想知道我的应用是否使用Meteor中的单元测试成功将文档添加到数据库。我正在使用practicalmeteor:mocha和chai。我遇到的问题是我不知道如何模拟this.userId,它一直告诉我我没有登录。

it('inserts the draft agenda document into the collection', function() {
      // TODO: mock document to insert into collection		  	
      // TODO: mock userId and Agenda.insert		  		
      this.userId = "Not an empty string";
      console.log("before spec, changing this.userId: " + this.userId) //is "Not an empty string"

      Meteor.call('createAgenda', mockAgenda, function(res) {
          console.log("callback with response: " + res); //You're not logged-in. [not-logged-in]		    		
          console.log("this.userId: " + this.userId) //is undefined
        }
}

感谢您的帮助,任何代码示例都会很棒。

1 个答案:

答案 0 :(得分:3)

说明

我想发表评论,但没有足够的声誉。所以这里有一些评论。由于您在服务器上进行测试,因此可以在没有回调的情况下调用Meteor方法。这将导致同步执行并简化您的测试。否则,您必须通过调用回调中的已完成功能让测试知道它已完成,请参阅mocha docs

使用mdg:validated-method

您可以使用 _execute 函数调用valited方法并提供它们执行的上下文。以下是todos sample project的示例。有关更多示例,您可以查看他们的ListsTodos测试。

it('makes a list private and updates the todos', function() {
  // Check initial state is public
  assert.isFalse(Lists.findOne(listId).isPrivate());

  // Set up method arguments and context
  const methodInvocation = {
    userId
  };
  const args = {
    listId
  };

  // Making the list private adds userId to the todo
  makePrivate._execute(methodInvocation, args);
  assertListAndTodoArePrivate();

  // Making the list public removes it
  makePublic._execute(methodInvocation, args);
  assert.isUndefined(Todos.findOne(todoId).userId);
  assert.isTrue(Todos.findOne(todoId).editableBy(userId));
});

使用标准方法

另一种可能性是将标准调用函数绑定到正确的上下文。请注意,这只是一个想法而未经过测试。

var methodInvocation = {
  userId: "some user id"
};

Meteor.call.bind(methodInvocation)('createAgenda', mockAgenda);