title: Spying on jQuery $('...') selector in jasmine
body: <p>When it comes to spying on jQuery functions (e.g. <code>bind</code>, <code>click</code>, etc) it is easy:</p>
  
  <pre><code>spyOn($.fn, "bind");
  </code></pre>
  
  <p>The problem is when you want to spy on <code>$('...')</code> and return defined array of elements.</p>
  
  <p>Things tried after reading other related answers on SO:</p>
  
  <pre><code>spyOn($.fn, "init").andReturn(elements); // works, but breaks stuff that uses jQuery selectors in afterEach(), etc
  spyOn($.fn, "merge").andReturn(elements); // merge function doesn't seem to exist in jQuery 1.9.1
  spyOn($.fn, "val").andReturn(elements); // function never gets called
  </code></pre>
  
  <p>So how do I do this? Or if the only way is to spy on <code>init</code> function how do I "remove" spy from function when I'm done so <code>afterEach()</code> routing doesn't break.</p>
  
  <p>jQuery version is 1.9.1.</p>
  
  <p><strong>WORKAROUND:</strong></p>
  
  <p>The only way I could make it work so far (ugly):</p>
  
  <pre><code>realDollar = $;
  try {
    $ = jasmine.createSpy("dollar").andReturn(elements);
    // test code and asserts go here
  } finally {
    $ = realDollar;
  }
  </code></pre>