Pages

Tuesday, April 23, 2013

Jasmine spying on jQuery selectors

Quick blog post about how to spy for jQuery selectors. Say I want to write something like the following:
var $element = $('div.my-element');
How would you write a Jasmine specification to drive this line of code in a Backbone.View function? Here it is:
it("find the element using a jQuery selector", function() {
   var spy = spyOn(jQuery.fn, 'find');
   this.view.doSomething();
   expect(spy).toHaveBeenCalledWith('div.my-element');
});
The reason you can do this is that $(selector, context) becomes $(context).find(selector). By default, selectors perform their searches within the DOM starting at the document root. However, an alternate context can be given for the search by using the optional second parameter to the $() function (from http://api.jquery.com/jQuery/#jQuery1). Had to write this down in a blog so I remember it again some day. Cheers!

9 comments:

  1. Going to use 'spyOn(jQuery.fn, 'find')' today.... Thanks for documenting this! (Also - learned a new word today 'equitation' from your sidebar....)

    ReplyDelete
    Replies
    1. Good luck and cool on learning about equitation.

      Delete
  2. Thanks! Very nice stuff!

    ReplyDelete
  3. $("#updateActionCommentsModel div.modal-body div#actionCommentsModelSuccessMessage").load(
    form.attr('action'),
    formData,
    function(data, responseStatus) {
    i want to mock server call but run this function on success and failure
    }
    );

    ReplyDelete
  4. I like this post because its very good information....
    Visit Best Astrologer in Rajanna Sircilla

    ReplyDelete
  5. Lovely blog post,Thanks for sharing this.
    visit here
    Best Sofa Repair Services in Agram

    ReplyDelete
  6. Thank you for your post. This is excellent information

    abhiram astrology center. Best Astrologer In brooks

    ReplyDelete