我刚刚开始使用Jasmine,请原谅新手问题但是在使用toHaveBeenCalledWith
时是否可以测试对象类型?
expect(object.method).toHaveBeenCalledWith(instanceof String);
我知道我能做到这一点,但它正在检查返回值而不是参数。
expect(k instanceof namespace.Klass).toBeTruthy();
答案 0 :(得分:92)
我发现了一个更加冷静的机制,使用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')
答案 1 :(得分:48)
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.mostRecentCall.args[0] instanceof String).toBeTruthy();
});
});