用 Jasmine 的 toHaveBeenCalledWith 方法使用对象类型

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

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

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

expect(k instanceof namespace.Klass).toBeTruthy();
76072 次浏览

toHaveBeenCalledWith is a method of a spy. So you can only call them on spy like described in the 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();
});


});

I've discovered an even cooler mechanism, using jasmine.any(), as I find taking the arguments apart by hand to be sub-optimal for legibility.

In 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')