最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Do you need spies to test if a function has been called in Jasmine? - Stack Overflow

programmeradmin4浏览0评论

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

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();
})
Share Improve this question edited Mar 23, 2017 at 0:36 Johannes 67.8k22 gold badges84 silver badges139 bronze badges asked Mar 22, 2017 at 22:09 jamesjames 4,0479 gold badges51 silver badges113 bronze badges 2
  • expect(populateNotes()) calls the function, it should be expect(populateNotes) – castletheperson Commented Mar 22, 2017 at 22:10
  • @4castle I don't think it's a duplicate, they're missing some other bits of jasmine as well. – Ehren Murdick Commented Mar 22, 2017 at 22:52
Add a ment  | 

1 Answer 1

Reset to default 6

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();
发布评论

评论列表(0)

  1. 暂无评论