我尝试使用Jasmine和Jasmine-JQuery来测试我正在处理的一些代码。但是,我编写了一个简单的测试来查看是否正在触发click
侦听器。我按照教程展示了如何设置间谍并使用它们来查看是否触发了事件。虽然这样可行,但当我添加jasmine-jquery匹配器toBeHidden()
时,它仍然返回false。我通过单击触发事件的按钮并选择它并在其上调用click()
来测试该方法。我也尝试将其置于setTimeOut
回调中以确保事件被触发,但它也无效。
这是我的倾听者
$("#b1").click(function(){
$("#p1").hide();
});
这是我的考试
describe("Hide, Show, Toggle Tests", function() {
var spyEvent;
function setUpToggleFixture() {
setFixtures('<div class="container">'
+ '<button id="b1">Hide Paragraph</button> <button id="b2">Show Paragraph</button> <button id="b3">Toggle Paragraph</button>'
+ '<p id="p1">Lorem</p></div>');
}
beforeEach(function() {
setUpToggleFixture();
});
it ("should invoke the hide click event.", function() {
spyEvent = spyOnEvent('#b1', 'click');
$('#b1').click());
expect('click').toHaveBeenTriggeredOn('#b1');
expect(spyEvent).toHaveBeenTriggered();
expect($("#p1")).toBeHidden();
});
});
答案 0 :(得分:0)
如果其他人在使用Jasmine测试JQuery时遇到任何困难,请记住,通过将任何代码包装在$(document).ready(function(){ });
中,它将阻止它被Jasmine测试。我的解决方案是将我的选择器包装在JS函数表达式中并在$(document).ready(function(){ });
中调用该函数,如此,
//my js file
$(document).ready(function(){
hide();
});
function hide(){
$("#b1").click(function(){
$("#p1").hide();
});
}
并按照这样测试
beforeEach(function() {
setFixtures('<div class="container">'
+ '<button id="b1">Hide Paragraph</button> <button id="b2">Show Paragraph</button> <button id="b3">Toggle Paragraph</button>'
+ '<p id="p1">Lorem</p></div>');
});
it ("should hide the paragraph.", function() {
hide(); //I need to call the method before running it now that I wrapped my
//method in a function expression
$('#b1').click();
expect($("#p1")).toBeHidden();
});