你是否需要间谍来测试是否在Jasmine中调用了一个函数?

时间:2017-03-22 22:09:01

标签: javascript jquery jasmine jasmine-jquery

我正在学习Jasmine,想知道以下测试是否有效?如果没有,有人可以解释原因吗?我一直在阅读一些教程,但找不到一个很好的解释,这些解释帮助我理解为什么我似乎无法正确编写如下的测试。

// 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();
})

1 个答案:

答案 0 :(得分:2)

你需要做两件事,首先你需要在点击之前监视这个功能。通常你会窥探这样一个对象成员的函数。 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();
相关问题