james
james

Reputation: 4047

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

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

Upvotes: 4

Views: 6119

Answers (1)

Ehren Murdick
Ehren Murdick

Reputation: 436

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

Upvotes: 6

Related Questions