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

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (12)

我创建了一个完整的简化示例,它复制了我所得到的问题。

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) ]);
    });
});

提问于
用户回答回答于

啊,我以为你已经附上的参数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));
    });
});
用户回答回答于

使用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));
  });
});

若要测试传递的值是否为函数,请执行以下操作:

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

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

扫码关注云+社区