5

我有两个要测试的原型:

var Person = function() {};

Person.prototype.pingChild = function(){
   var boy = new Child();
   boy.getAge();
}

var Child = function() {};

Child.prototype.getAge = function() {
    return 42;
};

我到底想测试什么:检查getAge()方法内部是否调用了该pingChild()方法

那是我尝试为此目的使用的 Jasmine 规格:

describe("Person", function() {
    it("calls the getAge() function", function() {
        var fakePerson = new Person();
        var chi = new Child();
        spyOn(fakePerson, "getAge");
        fakePerson.pingChild();
        expect(chi.getAge).toHaveBeenCalled();
    });
});

describe("Person", function() {
    it("calls the getAge() function", function() {
        var fakePerson = new Person();
        spyOn(fakePerson, "getAge");
        fakePerson.pingChild();
        expect(fakePerson.getAge).toHaveBeenCalled();
    });
});

describe("Person", function() {
    it("calls the getAge() function", function() {
        var fakePerson = new Person();
        var chi = new Child();
        spyOn(chi, "getAge");
        fakePerson.pingChild();
        expect(chi.getAge).toHaveBeenCalled();
    });
});

但他们都只显示错误:

  • getAge() 方法不存在
  • getAge() 方法不存在
  • 预期的间谍 getAge 已被调用

那么,有没有办法使用 Jasmine 测试这种情况,如果是的话 - 怎么做?

4

2 回答 2

10

You have yo spy on the prototype of Child object.

describe("Person", function () {
  it("calls the getAge() function", function () {
    var spy = spyOn(Child.prototype, "getAge");
    var fakePerson = new Person();
    fakePerson.pingChild();
    expect(spy).toHaveBeenCalled();
  });
});
于 2013-08-28T10:38:35.747 回答
2

我认为这是不可能的,因为无法从父对象外部访问内部对象。这完全取决于您的对象的范围。

您可以通过执行以下操作ChildPerson对象中公开您的对象:

var Person = function() {
    this.boy = new Child();
};

Person.prototype.pingChild = function(){
   this.boy.getAge();
}

接着:

describe("Person", function() {
    it("calls the getAge() function", function() {
        var fakePerson = new Person();
        var chi = fakePerson.boy;
        spyOn(chi, "getAge");
        fakePerson.pingChild();
        expect(chi.getAge).toHaveBeenCalled();
    });
});

或者委托Child外部Person对象的初始化:

var Person = function(child) {
    this.boy = child;
};

Person.prototype.pingChild = function(){
   this.boy.getAge();
}

接着:

describe("Person", function() {
    it("calls the getAge() function", function() {
        var chi = new Child();
        var fakePerson = new Person(chi);
        spyOn(chi, "getAge");
        fakePerson.pingChild();
        expect(chi.getAge).toHaveBeenCalled();
    });
});
于 2013-08-28T09:30:36.463 回答