Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stub a method of jasmine mock object?

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?

like image 768
Adelin Avatar asked Nov 30 '12 10:11

Adelin


People also ask

How do I stub a function in Jasmine?

stub. describe("A spy", function() { var foo, bar = null; beforeEach(function() { foo = { setBar: function(value) { bar = value; } }; spyOn(foo, 'setBar'). and. callThrough(); }); it("can call through and then stub in the same spec", function() { foo.

How do you mock a variable in Jasmine?

In your test: describe('LoginComponent', () => { ... let mockAuthService = new MockAuthService(); ... beforeEach(async(() => { TestBed. configureTestingModule({ imports: [...], declarations: [...], providers: [..., [ { provide: AuthService, useValue: mockAuthService }, ]], schemas: [...] }).


1 Answers

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'); 
like image 152
zbynour Avatar answered Sep 29 '22 12:09

zbynour