3

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();
})
Johannes
  • 64,305
  • 18
  • 73
  • 130
james
  • 3,989
  • 8
  • 47
  • 102

1 Answers1

5

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();
Ehren Murdick
  • 426
  • 3
  • 8
  • hmm... that didn't work, is it possible that the object isn't `window`? I literally have the function just sitting there... so window should be right... – james Mar 22 '17 at 23:25
  • You could define the function on window, just to make it testable. Instead of `function populateNotes(...` you can do `window.populateNotes = function(...` – Ehren Murdick Mar 22 '17 at 23:32
  • so explicitly defining the function on window still didn't cause the test to pass. however i can definitely verify that it's passing in a local server... any other ideas? – james Mar 22 '17 at 23:59
  • What's the failure message you're getting from jasmine exactly? – Ehren Murdick Mar 23 '17 at 00:02
  • `Error: Expected spy populatePreOrderNotes to have been called.` – james Mar 23 '17 at 00:24
  • @james Do you have screen hero? This would be a lot easier to debug if we could pair. (I work for the company that wrote jasmine) – Ehren Murdick Mar 23 '17 at 00:26