Stub out a jQuery selector call?

后端 未结 3 1862
别跟我提以往
别跟我提以往 2020-12-15 04:36

I\'m trying to get better at unit testing my JavaScript. I have the following code:

var categoryVal = $(\'#category\').val();
if (categoryVal === \'\') { 
           


        
3条回答
  •  盖世英雄少女心
    2020-12-15 05:08

    jQuery uses the css selector engine Sizzle under the hood and was decoupled so there's only a few places where it hooks in. You can intercept this to avoid any interaction with the dom.

    jQuery.find is the important one to alter to respond with anything you want. Sinon could be used here or temporarily swapping the function out.

    eg

    existingEngine = jQuery.find
    jQuery.find = function(selector){ console.log(selector) }
    $(".test")
    //>> ".test"
    jQuery.find = existingEngine
    

    you could also apply a specific catch condition with a fallback

    existingEngine = jQuery.find
    jQuery.find = function(selector){
      if(selector=='blah'}{ return "test"; }
      return existingEngine.find.apply(existingEngine, arguments)
    }
    

    In my recent work I have made a dummy object that responds like a dom node and wrapped that in a jQuery object. This will then respond to val() correctly and have all of the jquery methods present that it expects. In my case I'm simply pulling values from a form. If you are doing actual manipulation you might need to be more clever than this perhaps creating a temporary dom node with jQuery that represents what you expected.

    obj = {
      value: "blah",
      type: "text",
      nodeName: "input",
    }
    $(obj).val(); // "blah"
    

提交回复
热议问题