如何根据茉莉花单元测试中的其他对象测试功能

How to test function depending on other objects in jasmine unit test

本文关键字:其他 对象 测试 功能 何根 茉莉花 单元测试      更新时间:2023-09-26

我有一个茉莉花单元测试,用于一个名为 Event 的主干模型。

在这个模型中,我有一个函数:

getParticipants: function(){
  new Myappp.Collections.UsersCollection(
    this.get("participations").map(function(participation){
      return participation.get("user");
    });
  );
}

它有 4 个依赖项:

  • 用户模型
  • 用户集合
  • 参与模式
  • 参与集合

我想单独测试所有模型,因为这是最佳实践,但我不确定如何测试。

我正在使用 sinon.js 进行嘲笑和存根,但不知道如何在这种情况下正确使用它。

谢谢!

你的方法getParticipants做很多事情......实际上是3件事,所以我宁愿尝试让它专注于一件事:构建Myappp.Collections.UsersCollection。并将所有以前需要的计算转移到另一种方法。

然后,您可以专注于非常棘手的问题:模拟new电话

我会分 3 个阶段进行:

1. 将用户过滤器移动到另一个位置

我建议将其移动到Myapp.Collections.ParticipationsCollection中的方法,然后我们可以像这样从Event实例中调用它:

Myapp.Models.Event = 
  Backbone.Model.extend({
    getParticipants: function(){
      var usersArray   = this.get("participations").getUsers();
      var participants = new Myapp.Collections.UsersCollection(usersArray);
      return participants;
    }
  });
Myapp.Collections.ParticipationsCollection = 
  Backbone.Collection.extend({
    getUsers: function(){
      var users = 
        this.map(function(participation){
          return participation.get("user");
        });
      return users;
    }
  });

这样,我们可以轻松地模拟getUsers方法来测试我们的目标方法。

2. 包装,甚至更多,用户数组获得

我在上面的代码示例中,我们仍然在该行中有一个复杂的链方法调用this.get("participations").getUsers()我们可以将其移动到自定义方法也很容易模拟:

我们以这样的内容结束:

Myapp.Models.Event = 
  Backbone.Model.extend({
    getParticipants: function(){
      var usersArray   = this.getUsersArray();
      var participants = new Myapp.Collections.UsersCollection( usersArray );
      return participants;
    },
    getUsersArray: function(){
      return this.get("participations").getUsers();
    }
  });

3. 测试集合初始化

现在我们必须专注于模拟集合Myapp.Collections.UsersCollection,并使用适当的参数检查我们初始化和实体该集合的方法。

正确的参数是方法Event.getUsersArray()的结果,现在我们可以很容易地模拟它。

Sinon 特别期望检查是否已使用 new 调用了方法。

我的Jasmine/Sinon 方法并不准确,因为我没有测试该方法是否返回新的集合,我希望有人能提供更好的实现:

describe("Event", function() {
  beforeEach(function(){
    testModel = new Myapp.Models.Event();
  });
  it("getParticipants returns proper Collection", function() {
    var usersCollectionSpy = sinon.spy( Myapp.Collections, "UsersCollection" );
    var getUsersArrayMock = sinon.stub(testModel, "getUsersArray");
    getUsersArrayMock.returns( "usersArray" );
    testModel.getParticipants();
    expect( usersCollectionSpy.calledWith( "usersArray" ) ).toBeTruthy();
    expect( usersCollectionSpy.calledWithNew() ).toBeTruthy();
  });
});

检查 jsFiddle