Jasmine 的间谍 toHaveBeenCalled 方法存在问题
谁能告诉我为什么以下测试失败。
var Person = function() {};
Person.prototype.helloSomeone = function(toGreet) {
return this.sayHello() + " " + toGreet;
};
Person.prototype.sayHello = function() {
return "Hello";
};
describe("Person", function() {
it("calls the sayHello() function", function() {
var fakePerson = new Person();
spyOn(fakePerson, "sayHello");
fakePerson.helloSomeone("world");
expect(fakePerson.sayHello).toHaveBeenCalled();
});
});
我从此处获取它,他说它有效。我可以看到spyOn方法正在person对象上创建一个同名的包装函数,即fakePerson.sayHello正在对象上调用,而不是原型上。
非常感谢
Can anyone possibly tell me why the following test fails.
var Person = function() {};
Person.prototype.helloSomeone = function(toGreet) {
return this.sayHello() + " " + toGreet;
};
Person.prototype.sayHello = function() {
return "Hello";
};
describe("Person", function() {
it("calls the sayHello() function", function() {
var fakePerson = new Person();
spyOn(fakePerson, "sayHello");
fakePerson.helloSomeone("world");
expect(fakePerson.sayHello).toHaveBeenCalled();
});
});
I took it from here and he said it works. I can see the spyOn method is creating a wrapper function of the same name on the person object i.e. fakePerson.sayHello is being invoked on the object and not the prototype.
Many thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
测试失败了,因为我也在使用 jasmine-sinon.js。
The tests failed because I was also using jasmine-sinon.js.
您的测试用例的一个可能的问题是您没有指定应该调用原始方法。正确的行为如下(注意“andCallThrough”):
您可以查看 Jasmine 的文档页面,了解有关其他可能性的更多信息:https://github.com/pivotal/jasmine/wiki/Spies
编辑:快速浏览一下 jasmine-sinon 文档显示以下内容:
如果你想使用 jasmine-sinon,你必须使用他们的 API,而不是 Jasmine 的 API。编辑:自2012年2月起:
One possible problem with your test cases is that you haven't specified that the original method should be called. What would have a proper behavior is the following (note the "andCallThrough") :
You can see the documentation page of Jasmine for more information about the other possibility : https://github.com/pivotal/jasmine/wiki/Spies
Edit: A quick look at the jasmine-sinon documentation brings up the following:
If you want to use jasmine-sinon, you have to use their API and not the one of Jasmine.Edit: As of Feb 2012: