使用对象类型与Jasmine的“toHaveBeenCalledWith”方法

80

我刚开始使用Jasmine,请见谅我这个新手问题,使用toHaveBeenCalledWith时是否可以测试对象类型?

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

我知道我可以这样做,但是它检查的是返回值而不是参数。

expect(k instanceof namespace.Klass).toBeTruthy();
2个回答

126

我发现了一种更酷的机制,使用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')

25
jasmine.any(Function)也很方便。 - stefan.s
2
注意到它也适用于引用内部。例如:expect(obj.method).toHaveBeenCalledWith({done: jasmine.any(Function)})。非常有用。 - fncomp
2
截至本文撰写时,Jasmine在使用toHaveBeenCalledWith(...arguments)时不会检查new String('world')的相同实例。点击此处了解为什么这很重要。 - Fagner Brack
1
必须检查回调函数是否被调用,jasmin.any(Function) 拯救了我的生命,谢谢。 - user4676340

58

toHaveBeenCalledWith 是间谍的一个方法。因此,您只能像 docs 中所述的那样在间谍上调用它们。

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

});

1
Andreas,你添加 .toBeTruthy() 的原因是什么?看起来这是不必要的。 - jds
1
@gwg 如果没有匹配器,expect(foo) 就是一个空操作;如果没有 toBeTruthy() 调用,这一行代码将不会执行任何操作。请参见 http://jsfiddle.net/2doafezv/2/ 以获取证明。 - Mark Amery
8
这段内容已经过时了,obj.method.mostRecentCall 需要在 Jasmine 2.0 中改为 obj.method.calls.mostRecent()。此外,如另一个回答所述,使用 jasmine.any() 更清晰简洁。最后,这个答案需要一些时间才能得出结论;实际上,除了 expect(obj.method.mostRecentCall.args[0] instanceof String).toBeTruthy(); 之外,你写的其他东西都不是必要的来解释你自己。 - Mark Amery

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接