我刚开始使用Jasmine,请见谅我这个新手问题,使用toHaveBeenCalledWith
时是否可以测试对象类型?
expect(object.method).toHaveBeenCalledWith(instanceof String);
我知道我可以这样做,但是它检查的是返回值而不是参数。
expect(k instanceof namespace.Klass).toBeTruthy();
我刚开始使用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
是间谍的一个方法。因此,您只能像 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();
});
});
.toBeTruthy()
的原因是什么?看起来这是不必要的。 - jdsexpect(foo)
就是一个空操作;如果没有 toBeTruthy()
调用,这一行代码将不会执行任何操作。请参见 http://jsfiddle.net/2doafezv/2/ 以获取证明。 - Mark Ameryobj.method.mostRecentCall
需要在 Jasmine 2.0 中改为 obj.method.calls.mostRecent()
。此外,如另一个回答所述,使用 jasmine.any()
更清晰简洁。最后,这个答案需要一些时间才能得出结论;实际上,除了 expect(obj.method.mostRecentCall.args[0] instanceof String).toBeTruthy();
之外,你写的其他东西都不是必要的来解释你自己。 - Mark Amery
expect(obj.method).toHaveBeenCalledWith({done: jasmine.any(Function)})
。非常有用。 - fncomptoHaveBeenCalledWith(...arguments)
时不会检查new String('world')
的相同实例。点击此处了解为什么这很重要。 - Fagner Brackjasmin.any(Function)
拯救了我的生命,谢谢。 - user4676340