How to mute jasmine mock object method?

According to the Jasmine documentation, a layout can be created as follows:

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

How do you drown out one of these methods? For example, if you want to check what happens when a method throws an exception, how do you do it?

+48
javascript jasmine
Nov 30 '12 at 10:01
source share
2 answers

You need to associate method1 , method2 , as EricG commented, but not with andCallThrough() (or and.callThrough() in version 2.0). He will delegate the actual implementation.

In this case, you need to bind to and.callFake() and pass the function you want to call (it may throw an exception or whatever):

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

And then you can check:

 expect(yourFncCallingMethod1).toThrow('an-exception'); 
+85
Nov 30 '12 at
source share

If you are using Typescript, it is useful to use a method like Jasmine.Spy . In the answer above (weird, I have no comments for comments):

 (someObject.method1 as Jasmine.Spy).and.callFake(function() { throw 'an-exception'; }); 

I don’t know if I overdid it because I lack knowledge ...

For Typescript, I want:

  • Intellisense from the base type
  • Ability to mock methods used in functions

I found this useful:

 namespace Services { class LogService { info(message: string, ...optionalParams: any[]) { if (optionalParams && optionalParams.length > 0) { console.log(message, optionalParams); return; } console.log(message); } } } class ExampleSystemUnderTest { constructor(private log: Services.LogService) { } doIt() { this.log.info('done'); } } // I export this in a common test file // with other utils that all tests import const asSpy = f => <jasmine.Spy>f; describe('SomeTest', () => { let log: Services.LogService; let sut: ExampleSystemUnderTest; // ARRANGE beforeEach(() => { log = jasmine.createSpyObj('log', ['info', 'error']); sut = new ExampleSystemUnderTest(log); }); it('should do', () => { // ACT sut.doIt(); // ASSERT expect(asSpy(log.error)).not.toHaveBeenCalled(); expect(asSpy(log.info)).toHaveBeenCalledTimes(1); expect(asSpy(log.info).calls.allArgs()).toEqual([ ['done'] ]); }); }); 
+8
May 17 '17 at 16:52
source share



All Articles