2012-01-10 8 views
49

Acabo de empezar a usar Jasmine, por lo tanto, perdone la pregunta de novato, pero ¿es posible probar los tipos de objeto al usar toHaveBeenCalledWith?Uso de tipos de objetos con el método toHaveBeenCalledWith de Jasmine

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

Sé que podría esto, pero está comprobando el valor de retorno en lugar del argumento.

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

Respuesta

43

toHaveBeenCalledWith es un método de un espía. Por lo que sólo se les puede llamar de espionaje como se describe en el docs:

// 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.mostRecentCall.args[0] instanceof String).toBeTruthy(); 
    }); 

}); 
+1

Andreas, ¿hay alguna razón que agregó '.toBeTruthy()'? Parece que eso es innecesario. – gwg

+1

@gwg 'expect (foo)' sin un matcher es un no-op; la línea no haría nada sin la llamada 'toBeTruthy()'. Ver http://jsfiddle.net/2doafezv/2/ como prueba. –

+4

Esto está desactualizado; 'obj.method.mostRecentCall' necesita convertirse en [' obj.method.calls.mostRecent() '] (http://jasmine.github.io/2.0/introduction.html#section-Other_tracking_properties) en Jasmine 2.0. Además, usar 'jasmine.any()', como se describe en la otra respuesta, es más claro y atractivo. Finalmente, esta respuesta toma un tiempo para llegar al punto; esencialmente todo lo que escribiste además de 'expect (obj.method.mostRecentCall.args [0] instanceof String) .toBeTruthy();' no es realmente necesario para explicarte a ti mismo. –

84

he descubierto un mecanismo aún más frío, utilizando jasmine.any(), y yo intento tomando los argumentos separados con la mano para ser sub-óptimo para la legibilidad.

En 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') 
+16

jazmín.any (Función) es útil, también –

+1

Se dio cuenta de que también funciona dentro de las referencias. por ejemplo: 'expect (obj.method) .toHaveBeenCalledWith ({done: jasmine.any (Function)})'. Muy útil. – fncomp

+1

esta es la respuesta correcta. – Cam

Cuestiones relacionadas