Lucas
Lucas

Reputation: 3281

checking properties of arguments passed to function we spyOn

I'm trying to figure out (not successfully yet) if it's possible to check if js function I'm trying to mock with spyOn (jasmine) was called with the exact parameters I expected, for example consider function:

foo = function(date, array) {};

So far I can only make sure that the array was indeed passed like this:

spyOn(bar, 'foo').and.returnValue(somePromise.promise);
somePromise.resolve;
//call some function that calls 'foo' eventually...
expect(bar.foo).toHaveBeenCalledWith('10/12/2100', []);

I need to check if the array passed to this function was empty, how can I achieve this? Also if it's possible, how can I check if array passed to this function contained the string I wanted?

Thanks!

Upvotes: 1

Views: 5783

Answers (2)

Douglas
Douglas

Reputation: 37781

Replace and.returnValue with and.callFake, then pass in a function that stores the arguments before returning the promise. Then the arguments can be used for later expect tests.

Upvotes: 4

shieldgenerator7
shieldgenerator7

Reputation: 1756

I don't know Jasmine, so this will probably not be the answer you're looking for. On the other hand, it is a doable work around that you can implement in the mean time while you await your real answer.

If you have control over foo, then in the foo method you can tell it to set a global variable to its input parameter:

var fooParam;

var foo = function(array){
   fooParam = array;
}

Then in your other code, you can do:

if (fooParam != null){
   if (fooParam.contains(yourString)){
       //I'm not sure if "contains" is actually a method or not, 
       //but that's really a separate issue.
   }
}

So you set the global variable fooParam in the foo method and then you can use it later to do checking.

So there's a potential problem in that you might not have control over foo, such as if it's a system method. To work around that, replace all calls to foo with something like foo2, which you would define to have the same parameters and all it does is call foo and set the global variable. But if you have control of foo, then you don't need to do this.

The other potential problem is that foo will be called multiple times (such as if it's called within a loop). To circumvent this, you might make the global variable be an array list and have foo add its parameters to the array list instead of setting the variable. But if it's not called within a loop, or not called multiple times before it can be processed, then you don't need to do this.

I hope this helps while you're looking for the real answer

Upvotes: 1

Related Questions