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?
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.
In your test: describe('LoginComponent', () => { ... let mockAuthService = new MockAuthService(); ... beforeEach(async(() => { TestBed. configureTestingModule({ imports: [...], declarations: [...], providers: [..., [ { provide: AuthService, useValue: mockAuthService }, ]], schemas: [...] }).
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With