Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

can't get jasmine.any(Function) to work

I've created a complete simplified example that replicates the problem I'm getting.

function TestObj() {
    var self = this;
    self.getStuff = function(aString, callback) {
        // TODO
    }
}

describe("server communications", function() {
    it("it calls the server", function() {
        var obj = new TestObj();
        obj.getStuff = jasmine.createSpy();
        // swap the above line for this and it makes no difference
        // spyOn(obj, "getStuff");

        var functionVar = function() {
        };

        obj.getStuff("hello", functionVar);

        expect(obj.getStuff).toHaveBeenCalledWith(
                [ "hello", jasmine.any(Function) ]);
    });
});

Instead of a passing unit test, I get the following output:

Expected spy to have been called with: [ [ 'hello',<jasmine.any(function Function() { [native code] })> ] ] but was called with: [ [ 'hello', Function ] ]

Why is it not recognising that the functions I pass in (function (){}) are actually functions? Whats that native code stuff it is expecting? Anyone else had this issue with jasmine.any(Function)? Thankyou!

EDITED

I tried using spyOn instead of jasmine.createSpy() and it makes no difference. I tried just a single argument and it works. Introducing the first string argument breaks the jasmine.any(Function) - any ideas?

like image 709
Mike S Avatar asked May 16 '12 01:05

Mike S


2 Answers

Ah, I thought you had to enclose the arguments of expect().toHaveBeenCalledWith in an Array[]. Silly me. Here is a working version:

function TestObj() {
    var self = this;
    self.getStuff = function(aString, callback) {
        // TODO
    }
}

describe("server communications", function() {
    it("it calls the server", function() {
        var obj = new TestObj();
        obj.getStuff = jasmine.createSpy();
        // swap the above line for this and it makes no difference
        // spyOn(obj, "getStuff");

        var functionVar = function() {
        };

        obj.getStuff("hello", functionVar);

        expect(obj.getStuff).toHaveBeenCalledWith("hello", jasmine.any(Function));
    });
});
like image 102
Mike S Avatar answered Oct 13 '22 23:10

Mike S


The Problem is the way you create your spy, using spyOnseems to work as expected:

describe("test", function() {
  return it("is function", function() {
    var a = {b: function(){}};
    spyOn(a, 'b');
    a.b(function(){});
    expect(a.b).toHaveBeenCalledWith(jasmine.any(Function));
  });
});

You could also write your own Matcher to test if the passed value is a function:

describe('test',function(){
  it('is function',function(){

    this.addMatchers({
      isFunction: function() {
        return typeof this.actual  === 'function';
      }
    });
    expect(function(){}).isFunction();
  });
});

EDITED: codified the first code chunk

like image 7
Andreas Köberle Avatar answered Oct 13 '22 21:10

Andreas Köberle