Подтвердить что ты не робот

Использование типов объектов с помощью метода Jasmine toHaveBeenCalledWith

Я только начал использовать Jasmine, поэтому, пожалуйста, простите вопрос новичков, но можно ли тестировать типы объектов при использовании toHaveBeenCalledWith?

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

Я знаю, что могу это сделать, но проверять возвращаемое значение, а не аргумент.

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

Ответ 1

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

});

Ответ 2

Я обнаружил еще более холодный механизм, используя 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')