我有两个原型(prototype)要测试:
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() method does not exist
- getAge() method does not exist
- Expected spy getAge to have been called
那么,是否有任何方法可以使用 Jasmine 测试此类情况,如果是的话 - 如何完成?
最佳答案
你已经监视了 Child
对象的原型(prototype)。
describe("Person", function () {
it("calls the getAge() function", function () {
var spy = spyOn(Child.prototype, "getAge");
var fakePerson = new Person();
fakePerson.pingChild();
expect(spy).toHaveBeenCalled();
});
});
关于javascript - Jasmine:如何监视内部对象方法调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18483959/