Do you need spies to test if a function has been called in Jasmine?

我是研究僧i 提交于 2020-12-13 03:02:23

问题


Am learning Jasmine, wondering if the following test would be valid? And if not, can someone explain why? I've been reading a number of tutorials and can't find a good explanation that has helped me understand why I can't seem to write a test like the one below correctly.

// 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:


You need to do two things, first you need to spy on the function before the click. Normally you would spy on a function like this that is a member of an object. Where is populateNotes defined? You need a reference to it somehow.

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


来源:https://stackoverflow.com/questions/42963576/do-you-need-spies-to-test-if-a-function-has-been-called-in-jasmine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!