Shayan Zafar
Shayan Zafar

Reputation: 113

Jasmine: Spying on multiple Jquery Selectors that call same function

In JavaScript, I have a function I'd like to test using Jasmine 2.1.3:

   function someFunction(){
     var $firstSelector = $("#firstSelector").val();
     var $secondSelector = $("#secondSelector").val();

     // some function logic
}

How can I spy on the $firstSelector.val() and $secondSelector.val() to provide defined return values for each to test my function? e.g (i want to spy on $firstSelector.val() to return "Hello" and $secondSelector.val() to return "World").

I have read answers that allude to spying on the generic $.fn and returning a value for val. But I am unsure how it will give me the control of manually setting return values for different JQuery selector passed in. Is there a concept here I am missing?

Is it possible to have this level of control in terms of mocking JQuery $(someSelectorVariable).val() with different selectors as parameters?

Upvotes: 1

Views: 373

Answers (1)

Shayan Zafar
Shayan Zafar

Reputation: 113

So i basically spied on the $.fn and used callFake. Within the annonymous function i was able to access the this.selector property. It was simple from there. I hope this helps anyone!

spyOn($.fn, "val").and.callFake(function () {
                switch (this.selector) {
                    case "#firstSelector":
                        return "somethingElse";
                    case "#secondSelector":
                        return "";
                    default:
                        return "";
                }
});

Upvotes: 1

Related Questions