Javascript 在 Jasmine 的 toHaveBeenCalledWith 方法中使用对象类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8801060/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 07:33:30  来源:igfitidea点击:

Using object types with Jasmine's toHaveBeenCalledWith method

javascripttddbddjasmine

提问by screenm0nkey

I've just started using Jasmine so please forgive the newbie question but is it possible to test for object types when using toHaveBeenCalledWith?

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

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

I know I could this but it's checking the return value rather than the argument.

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

expect(k instanceof namespace.Klass).toBeTruthy();

采纳答案by Andreas K?berle

toHaveBeenCalledWithis a method of a spy. So you can only call them on spy like described in the docs:

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

});

回答by Wolfram Arnold

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

我发现了一种更酷的机制,使用jasmine.any" rel="noreferrer">jasmine.any(), 因为我发现手动分离参数对于易读性来说不是最佳的。

In CoffeeScript:

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