How to Mock JSNLog in Jasmine Unit Tests of Angular Code
One of the development teams at work implemented JSNLog to log from JavaScript in an Angular application we're working on, but even though the documentation to get this set up and running was very clear, the way to get it mocked for unit testing was not.
Fortunately, it's not too difficult. The key in getting this to work was to spy on the JL function and have it return a mock with spy methods for the different logging methods (debug(), trace(), etc). Then set it up in your providers declaration.
Here's the mock object:
In your spec, instantiate an instance of that and then spy on the JL function and return that instance:
And finally, set up a provider for it in your providers array when configuring your testing module:
This did the trick for us. :)
Fortunately, it's not too difficult. The key in getting this to work was to spy on the JL function and have it return a mock with spy methods for the different logging methods (debug(), trace(), etc). Then set it up in your providers declaration.
Here's the mock object:
export class JLMock { trace = jasmine.createSpy('trace'); debug = jasmine.createSpy('debug'); info = jasmine.createSpy('info'); warn = jasmine.createSpy('warn'); error = jasmine.createSpy('error'); fatal = jasmine.createSpy('fatal'); }
In your spec, instantiate an instance of that and then spy on the JL function and return that instance:
let jlMock = new JLMock(); let JL = jasmine.createSpy('JL').and.returnValue(jlMock);
And finally, set up a provider for it in your providers array when configuring your testing module:
{ provide: 'JSNLOG', useValue: JL },
This did the trick for us. :)
Comments
Post a Comment