如何用 Jasmine 模拟 JQuery?
如何测试某个 JQuery 选择器是否已使用 Jasmine 执行?我正在尝试执行以下操作:
spyOn($.fn, 'init').andCallThrough();
// my code
expect($.init).toHaveBeenCalled();
但是在此调用之后, $('div')
返回 Object {selector="div", context=document, NaN=div.spec, more ...}
,尽管它必须返回(并且 $.fn.init('div')
确实返回它):[div.jasmine_reporter, div.banner, div.logo,还有 4 个...]
。这个东西自然会破坏代码,因为 JQuery 对象不再可用。
示例:
假设我想测试是否已调用 JQuery 选择器,我写道:
it('tests', function() {
spyOn($.fn, 'init').andCallThrough();
$('html');
expect($.init).toHaveBeenCalled();
});
这会导致 Jasmine 出现错误:错误:预期有间谍,但未定义。
。然后我在 FireBug 中的 $('html') 行上设置了一个断点,当我到达那里并尝试观察 $('html')
的值时,我得到:
Object { selector="html", context=document, NaN=html, more...}
如果我评论out spyOn
,在该行 $('html')
的计算结果为:
[html]
这也是我期望通过 spyOn
看到的结果。
How can I test that a certain JQuery selector has been executed with Jasmine? I'm trying to do the following:
spyOn($.fn, 'init').andCallThrough();
// my code
expect($.init).toHaveBeenCalled();
But after this call, $('div')
returns Object { selector="div", context=document, NaN=div.spec, more...}
, though it has to return (and $.fn.init('div')
does return it): [div.jasmine_reporter, div.banner, div.logo, 4 more...]
. This stuff naturally breaks the code since the JQuery object is no longer usable.
Example:
Say I want to test that a JQuery selector has been called, I write:
it('tests', function() {
spyOn($.fn, 'init').andCallThrough();
$('html');
expect($.init).toHaveBeenCalled();
});
This result it an error from Jasmine: Error: Expected a spy, but got undefined.
. Then I set a breakpoint in FireBug on $('html') line and when I get there and try to watch, what the value of $('html')
is, I get:
Object { selector="html", context=document, NaN=html, more...}
If I comment out spyOn
, on that line $('html')
evaluates to:
[html]
Which is what I expected to see with spyOn
as well.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
好吧,看起来 Jasmine 通过用包装版本替换被监视的对象来进行间谍活动,这似乎搞乱了 jQuery 的整体,因为(来自 jQuery 源代码):
我建议尝试监视 init 使用的函数之一,特别是“合并”。如果您查看 jQuery 代码,您会发现任何 HTML=>DOM 内容最终都会通过合并调用返回:(
如果您碰巧查看 jQuery 1.5.1 的源代码,则为第 152 行)。
通过监视合并,您应该能够测试您正在测试的任何内容,而不会无意中替换 jQuery 的内容。
Well it looks like Jasmine does it's spy stuff by replacing the spied-on object with a wrapped version, and that seems to be messing up jQuery as a whole because (from the jQuery source code):
I'd suggest trying to spy on one of the functions that init uses, specifically "merge". If you look at the jQuery code, you'll see that any HTML=>DOM stuff ultimately gets returned through a merge call:
(that's line 152 if you happen to be looking at the source of jQuery 1.5.1).
By spying on merge you should be able to test whatever you're testing, without inadvertently replacing the guts of jQuery.