wpp
wpp

Reputation: 7303

How to stub javascript dependencies (jquery) in jasmine?

I have some legacy code on my hands which was written with/relies upon the following stack:

Before I change anything in the code, I figured I'd write tests for it, so I can make nothing brakes :).

I'm running into some issues, because the code I want to write tests for relies on jquery to define some "constants" e.g:

var WIDTH = $(document).width();

I guess there is no way around stubbing.

  1. Should I include jquery in jasmine and try to spec the document?
  2. Or not include jquery in jasmine and stub $?

I fear I might be going down the wrong direction and would much appreciate some guidance (code snippets much appreciated). Thanks for helping a noob out!

Upvotes: 1

Views: 479

Answers (1)

Schleis
Schleis

Reputation: 43700

I would include jQuery and mock the functions that it calls. In your example, I would do.

spyOn($.fn, 'width').andReturn(300); //Return a value that you expect to be used

Jasmine spies have a property calls that is an array of all the calls and one thing that I have done is examine the calls entries and you can check the calling object. That being a jQuery object it has the property selector which you can expect to be equal to document

expect($.fn.width.calls[0].object.selector).toEqual(document);

Though remember you are trying to test the expected behavior of the code, not that each step of the code is completed as it is written. Trying to test that certain lines exists will prevent you from easily refactoring.

Upvotes: 1

Related Questions