javascript 在茉莉花测试中存根 e.preventDefault()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15941181/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Stubbing e.preventDefault() in a jasmine test
提问by Huy
I recently added an e.preventDefault()
to one of my javascript functions and it broke my jasmine spec. I've tried spyOn(e, 'preventDefault').andReturn(true);
but I get e
is undefined error. How do I stub e.preventDefault()?
我最近e.preventDefault()
在我的一个 javascript 函数中添加了一个,它破坏了我的 jasmine 规范。我试过了,spyOn(e, 'preventDefault').andReturn(true);
但我得到的e
是未定义的错误。我如何存根e.preventDefault()?
showTopic: function(e) {
e.preventDefault();
midParent.prototype.showTopic.call(this, this.model, popup);
this.topic.render();
}
it("calls the parent", function() {
var parentSpy = spyOn(midParent.prototype, "showTopic");
this.view.topic = {
render: function() {}
};
this.view.showTopic();
expect(parentSpy).toHaveBeenCalled();
});
回答by zbynour
Another way to create mock object (with spies you need) is to use jasmine.createSpyObj()
.
Array containing spy names have to be passed as second parameter.
创建模拟对象(使用您需要的间谍)的另一种方法是使用jasmine.createSpyObj()
. 包含间谍名称的数组必须作为第二个参数传递。
var e = jasmine.createSpyObj('e', [ 'preventDefault' ]);
this.view.showTopic(e);
expect(e.preventDefault).toHaveBeenCalled();
回答by Andreas K?berle
You have to pass an object with a field preventDefault that holds your spy:
您必须传递一个带有 preventDefault 字段的对象,该对象包含您的间谍:
var event = {preventDefault: jasmine.createSpy()}
this.view.showTopic(event);
expect(event.preventDefault).toHaveBeenCalled
回答by Winnemucca
This is very similar to approaches on top. I just mocked out the event and passed preventDefault with an sinon spy. The difference was that I had to identify the type which was a click on my test.
这与顶部的方法非常相似。我只是模拟了这个事件,并通过一个 sinon 间谍传递了 preventDefault 。不同之处在于我必须确定我的测试点击的类型。
var e = {
type: 'click',
preventDefault: sinon.spy()
};