javascript-将对象类型与Jasmine的toHaveBeenCalledWith方法一起使用

我刚刚开始使用Jasmine,因此请原谅新手问题,但是使用toHaveBeenCalledWith时是否可以测试对象类型?

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

我知道我可以,但是它正在检查返回值而不是参数。

expect(k instanceof namespace.Klass).toBeTruthy();
screenm0nkey asked 2019-11-15T22:31:21Z
2个解决方案
98 votes

我发现了一个更凉爽的机制,使用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')
Wolfram Arnold answered 2019-11-15T22:32:34Z
52 votes

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

});
Andreas Köberle answered 2019-11-15T22:32:08Z
translate from https://stackoverflow.com:/questions/8801060/using-object-types-with-jasmines-tohavebeencalledwith-method