Javascript 您是否需要间谍来测试Jasmine中是否调用了函数?
我正在学习茉莉花,想知道下面的测试是否有效?如果没有,有人能解释一下原因吗?我已经阅读了很多教程,但找不到一个好的解释来帮助我理解为什么我不能正确地编写下面这样的测试Javascript 您是否需要间谍来测试Jasmine中是否调用了函数?,javascript,jquery,jasmine,jasmine-jquery,Javascript,Jquery,Jasmine,Jasmine Jquery,我正在学习茉莉花,想知道下面的测试是否有效?如果没有,有人能解释一下原因吗?我已经阅读了很多教程,但找不到一个好的解释来帮助我理解为什么我不能正确地编写下面这样的测试 // spec describe("when cart is clicked", function() { it("should call the populateNotes function", function() { $("#show-cart").click() expect(pop
// spec
describe("when cart is clicked", function() {
it("should call the populateNotes function", function() {
$("#show-cart").click()
expect(populateNotes()).toHaveBeenCalled();
})
})
// code
$("#show-cart").click(function() {
populateNotes();
})
您需要做两件事,首先需要在单击之前监视函数。通常,您会监视这样一个函数,它是对象的成员。人口在哪里定义?你需要以某种方式引用它
// This might work, if the function is defined globally.
spyOn(window, 'populateNotes');
// Then do your action that should result in that func being called
$("#show-cart").click();
// Then your expectation. The expectation should be on the function
// itself, not on the result. So no parens.
expect(window.populateNotes).toHaveBeenCalled();
expect(populateNotes())
调用函数,它应该是expect(populateNotes)
@4castle我不认为它是重复的,它们还缺少一些茉莉花的其他部分。嗯。。。这不起作用,对象是否可能不是窗口
?我真的有这个功能只是坐在那里。。。所以window应该是正确的…您可以在window上定义函数,只是为了使其可测试。您可以执行window.populateNotes=function,而不是function populateNotes(…
(…
因此,在window上显式定义函数仍然没有导致测试通过。但是,我可以肯定地验证它正在本地服务器中传递…还有其他想法吗?您从jasmine那里得到的失败消息是什么?错误:预期已调用spy populatePreOrderNotes。