[英]Jasmine: how to spy on inner object method call?
我有兩個要測試的原型:
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來測試這種情況,如果可以的話,怎么辦?
您對Child
對象的原型有間諜。
describe("Person", function () {
it("calls the getAge() function", function () {
var spy = spyOn(Child.prototype, "getAge");
var fakePerson = new Person();
fakePerson.pingChild();
expect(spy).toHaveBeenCalled();
});
});
我認為這是不可能的,因為內部對象無法從父對象外部訪問。 這完全取決於對象的范圍。
您可以通過執行以下操作在Person
對象中公開Child
對象:
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();
});
});
或在Person
對象之外委托Child
的初始化:
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();
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.