不能让jasmine.any(功能)工作

Mik*_*e S 20 javascript jasmine

我已经创建了一个完整的简化示例,可以复制我遇到的问题.

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) ]);
    });
});
Run Code Online (Sandbox Code Playgroud)

我得到以下输出,而不是通过单元测试:

预期的间谍被调用:[['hello',<jasmine.any(function Function(){[native code]})>]]但被调用:[['hello',Function]]

为什么它没有认识到我传入的函数(function(){})实际上是函数?是什么原因代码的东西是什么?其他人有jasmine.any(Function)这个问题吗?谢谢!

EDITED

我尝试使用spyOn而不是jasmine.createSpy(),它没有任何区别.我只尝试了一个参数并且它有效.引入第一个字符串参数会破坏jasmine.any(Function) - 任何想法?

Mik*_*e S 35

啊,我以为你已经附上的参数expect().toHaveBeenCalledWith中的Array[].傻我.这是一个工作版本:

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));
    });
});
Run Code Online (Sandbox Code Playgroud)


And*_*rle 7

问题是你创建间谍的方式,使用spyOn似乎按预期工作:

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));
  });
});
Run Code Online (Sandbox Code Playgroud)

您也可以编写自己的Matcher来测试传递的值是否为函数:

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

    this.addMatchers({
      isFunction: function() {
        return typeof this.actual  === 'function';
      }
    });
    expect(function(){}).isFunction();
  });
});
Run Code Online (Sandbox Code Playgroud)

编辑:编码第一个代码块