将对象类型与茉莉花的tohavebeencalledwith方法一起使用
-
25-10-2019 - |
题
我刚刚开始使用茉莉花,所以请原谅新手问题,但是在使用时是否可以测试对象类型 toHaveBeenCalledWith
?
expect(object.method).toHaveBeenCalledWith(instanceof String);
我知道我可以这样做,但是它正在检查返回值而不是参数。
expect(k instanceof namespace.Klass).toBeTruthy();
解决方案
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();
});
});
其他提示
我发现了一个更酷的机制 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')
不隶属于 StackOverflow