How to stub a method of jasmine mock object?

Adelin picture Adelin · Nov 30, 2012 · Viewed 76.9k times · Source

According to the Jasmine documentation, a mock can be created like this:

jasmine.createSpyObj(someObject, ['method1', 'method2', ... ]);

How do you stub one of these methods? For example, if you want to test what happens when a method throws an exception, how would you do that?

Answer

zbynour picture zbynour · Nov 30, 2012

You have to chain method1, method2 as EricG commented, but not with andCallThrough() (or and.callThrough() in version 2.0). It will delegate to real implementation.

In this case you need to chain with and.callFake() and pass the function you want to be called (can throw exception or whatever you want):

var someObject = jasmine.createSpyObj('someObject', [ 'method1', 'method2' ]);
someObject.method1.and.callFake(function() {
    throw 'an-exception';
});

And then you can verify:

expect(yourFncCallingMethod1).toThrow('an-exception');