Search code examples
javascripttestingjasminebdd

How do I test HTML DOM click() using Jasmine?


I'm pretty new to Jasmine testing, and I'm facing a small problem. I have a function like this:

"redirectPage.js"

function clickThis(){
    document.getElementById("link").click();
}

How do I test that this function has been called / triggered in my test?

This is my test currently:

describe('Test redirectPage', function() {
    beforeEach(function() {
        loadFixtures("redirectPageFixture.html");
    });

    it(" checks if the clickThis() method is triggered", function(){
        var spyEvent = spyOnEvent("#link", "click");
        ("#link").trigger("click");
        expect(spyEvent).toHaveBeenTriggered();
    });
});    

But doing this, gives me this error:

TypeError: "#link".click is not a function

How do I fix this test? Any help is greatly appreciated!

UPDATE:

This is my fixture:

<html>
 <head>
  <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
  <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap-theme.min.css">
  <script src="http://code.jquery.com/jquery.min.js" defer>
  <link rel="stylesheet" href="css/navbar.css">
  <link rel="stylesheet" href="css/searchControl.css">
  <script type="text/javascript" src="src/main/resources/assets/js/redirectPage.js" defer>
  <script src="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/js/bootstrap.min.js"></script>
 </head>
 <body onload="setTimeout('clickThis();',3000);>
  <p><a id=link href = "www.google.com">click here</a></p>
 </body>
</html>

Solution

  • I finally figured out what I was doing wrong. I was creating the spy on my object, but wasn't actually calling the function that i needed. If any one is interested, this is my test case now:

    it(" checks if the clickThis() method is triggered", function(){
        var spyEvent = spyOnEvent("#link", "click");
        clickThis();
        expect(spyEvent).toHaveBeenTriggered();
    });
    

    Thank you everyone for your inputs! :)