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:

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

Popular Posts

Resolving the "n timer(s) still in the queue" Error In Angular Unit Tests

How to Get Norton Security Suite Firewall to Allow Remote Desktop Connections in Windows

How to Determine if a Column Exists in a DataReader

Silent Renew and the "login_required" Error When Using oidc-client

Fixing the "Please add a @Pipe/@Directive/@Component annotation" Error In An Angular App After Upgrading to webpack 4