DOM events

There will be times when the code you are writing must respond to DOM events, such as onclick or onselect. Luckily, writing tests that need these DOM events can also be simulated by using jQuery, jasmine-jquery, and spies as follows:

describe("click event tests", () => { 
    it("should trigger an onclick DOM event", () =>{ 
        setFixtures(` 
            <script> 
            function handle_my_click_div_clicked() {  
                // do nothing at this time 
            } 
            </script>         
            <div id='my_click_div' 
            onclick='handle_my_click_div_clicked()'>Click Here</div>`); 
        var clickEventSpy = spyOnEvent('#my_click_div', 'click'); 
        $('#my_click_div').click(); 
        expect(clickEventSpy).toHaveBeenTriggered(); 
    }); 
});

This test is again calling the setFixtures function from the jasmine-jquery library. This setFixtures function is doing two things. Firstly, it is defining a function within a <script> tag named handle_my_click_div_clicked. Secondly, it is defining a <div> with an ID of my_click_div, and then attaching the DOM event of onclick to call the handle_my_click_div_clicked() function. This single function call is therefore setting up all of the required HTML for the onclick event. Without this <script> tag, running our tests will produce an error:

ReferenceError: handle_my_click_div_clicked is not defined

Our test then sets up a Jasmine spy named clickEventSpy. This spy uses the jasmine-jquery function named spyOnEvent, which takes two parameters—a jQuery selector for the element to spy on, and a DOM event name.

We then use jQuery to trigger the event by calling $('#my_click_div').click(). Remember that the default behavior of a spy is to hijack the function definition and call our spy instead. The last line of this test is our expectation, where we are expecting the spy to have been triggered. The toHaveBeenTriggered function is a Jasmine matcher that is provided by the jasmine-jquery library.

jQuery and DOM manipulation provide us with a way of filling in forms, clicking on the submit, cancel, and ok buttons, and generally simulating user interaction with our application. We can easily write full acceptance or user acceptance tests within Jasmine using these techniques—further solidifying our application against errors and change.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.174.174