Использование типов объектов с методом Жасмина toHaveBeenCalledWith - PullRequest
53 голосов
/ 10 января 2012

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

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

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

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

Ответы [ 2 ]

93 голосов
/ 02 февраля 2012

Я обнаружил еще более крутой механизм, использующий jasmine.any" rel="noreferrer">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')
50 голосов
/ 10 января 2012

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

});
...