Javascript Jasmine:如何监视内部对象方法调用?
我想测试两个原型:Javascript Jasmine:如何监视内部对象方法调用?,javascript,unit-testing,testing,bdd,jasmine,Javascript,Unit Testing,Testing,Bdd,Jasmine,我想测试两个原型: var Person = function() {}; Person.prototype.pingChild = function(){ var boy = new Child(); boy.getAge(); } var Child = function() {}; Child.prototype.getAge = function() { return 42; }; 我要测试的内容:检查getAge()方法是否在pingChild()方法中调用
var Person = function() {};
Person.prototype.pingChild = function(){
var boy = new Child();
boy.getAge();
}
var Child = function() {};
Child.prototype.getAge = function() {
return 42;
};
我要测试的内容:检查getAge()
方法是否在pingChild()方法中调用
这就是我尝试用于此目的的茉莉花规格:
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()方法不存在
- 预期已调用spy getAge
那么,有没有办法用Jasmine来测试这种情况,如果有,怎么做?我认为这是不可能的,因为从父对象外部无法访问内部对象。这都是关于对象的范围
通过执行以下操作,您可以在Person
对象中公开您的子对象
对象:
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();
});
});
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();
});
});
或者将子对象
的初始化委托给人员
对象外部:
var Person = function(child) {
this.boy = 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();
});
});
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();
});
});
你可以监视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();
});
});