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'] ]); }); });
Eric Swanson May 17 '17 at 16:52 2017-05-17 16:52
source share