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

scr*_*key 57 javascript tdd bdd jasmine

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

expect(object.method).toHaveBeenCalledWith(instanceof String);
Run Code Online (Sandbox Code Playgroud)

我知道我可以做到这一点,但它正在检查返回值而不是参数.

expect(k instanceof namespace.Klass).toBeTruthy();
Run Code Online (Sandbox Code Playgroud)

Wol*_*old 101

我已经发现了一种更加冷却的机制,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')
Run Code Online (Sandbox Code Playgroud)

  • jasmine.any(Function)也很方便 (22认同)
  • 注意到它也适用于参考文献.例如:`expect(obj.method).toHaveBeenCalledWith({done:jasmine.any(Function)})`.很有用. (2认同)
  • 截至撰写本文时,Jasmine在使用`toHaveBeenCalledWith(... arguments)`时不检查"new String('world')`的相同实例.[点击这里](https://medium.com/@fagnerbrack/mocking-can-lean-to-nondeterministic-tests-4ba8aef977a0)了解为什么这很重要. (2认同)

And*_*rle 52

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

});
Run Code Online (Sandbox Code Playgroud)

  • 这个已经过期了; `obj.method.mostRecentCall`需要在Jasmine 2.0中成为[`obj.method.calls.mostRecent()`](http://jasmine.github.io/2.0/introduction.html#section-Other_tracking_properties).另外,使用`jasmine.any()`,如另一个答案中所述,更清晰,更可爱.最后,这个答案需要一段时间才能达到目的; 基本上你写的除了`expect(obj.method.mostRecentCall.args [0] instanceof String).toBeTruthy();`之后你真的需要解释自己. (7认同)