Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using object types with Jasmine's toHaveBeenCalledWith method

I've just started using Jasmine so please forgive the newbie question but is it possible to test for object types when using 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();
like image 868
screenm0nkey Avatar asked Jan 10 '12 09:01

screenm0nkey


2 Answers

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

In 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')
like image 189
Wolfram Arnold Avatar answered Nov 12 '22 16:11

Wolfram Arnold


toHaveBeenCalledWith is a method of a spy. So you can only call them on spy like described in the 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.calls.mostRecent().args[0] instanceof String).toBeTruthy();
  });

});
like image 40
Andreas Köberle Avatar answered Nov 12 '22 17:11

Andreas Köberle