簡體   English   中英

使用Jasmine的toHaveBeenCalledWith方法的對象類型

[英]Using object types with Jasmine's toHaveBeenCalledWith method

我剛剛開始使用Jasmine,請原諒新手問題但是在使用toHaveBeenCalledWith時是否可以測試對象類型?

expect(object.method).toHaveBeenCalledWith(instanceof String);

我知道我可以做到這一點,但它正在檢查返回值而不是參數。

expect(k instanceof namespace.Klass).toBeTruthy();

我發現了一個更酷的機制,使用jasmine.any() ,因為我發現手動分開的參數是易讀性的次優。

在CoffeeScript中:

obj = {}
obj.method = (arg1, arg2) ->

describe "callback", ->

   it "should be called with 'world' as second argument", ->
     spyOn(obj, 'method')
     obj.method('hello', 'world')
     expect(obj.method).toHaveBeenCalledWith(jasmine.any(String), 'world')

toHaveBeenCalledWith是一個間諜的方法。 所以你只能在間諜上調用它們,如文檔中所述:

// your class to test
var Klass = function () {
};

Klass.prototype.method = function (arg) {
  return arg;
};


//the test
describe("spy behavior", function() {

  it('should spy on an instance method of a Klass', function() {
    // create a new instance
    var obj = new Klass();
    //spy on the method
    spyOn(obj, 'method');
    //call the method with some arguments
    obj.method('foo argument');
    //test the method was called with the arguments
    expect(obj.method).toHaveBeenCalledWith('foo argument');   
    //test that the instance of the last called argument is string 
    expect(obj.method.calls.mostRecent().args[0] instanceof String).toBeTruthy();
  });

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM