23

発生している問題を再現する完全に簡略化された例を作成しました。

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

ユニットテストに合格する代わりに、次の出力が得られます。

スパイは[['hello'、<jasmine.any(function Function(){[ネイティブコード]})>]]で呼び出されたと予想されますが、[['hello'、Function]]で呼び出されました

渡した関数(function(){})が実際に関数であると認識されないのはなぜですか?それが期待しているネイティブコードのものは何ですか?他の誰かがjasmine.any(Function)でこの問題を抱えていましたか?ありがとうございました!

編集済み

jasmine.createSpy()の代わりにspyOnを使用してみましたが、違いはありません。私はただ一つの議論を試みました、そしてそれはうまくいきます。最初の文字列引数を導入すると、jasmine.any(Function)が壊れます-アイデアはありますか?

4

2 に答える 2

39

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));
    });
});
于 2012-05-17T00:50:34.833 に答える
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));
  });
});

渡された値が関数であるかどうかをテストするために、独自のマッチャーを作成することもできます。

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

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

編集:最初のコードチャンクを成文化した

于 2012-05-16T08:46:29.093 に答える