Checking log4js output in your node.js testsuite

This post will teach you how to test  log4js  log statements in your code.

You can also find the code below in the src/log4js-unittest dir of my blog code repository.

Let’s say that we have written this simple node.js module, foo.js .

It would be good to verify that logSomething()  actually logs something. Let’s use this mocha test file skeleton foo.spec.js :

We obviously cannot test logSomething() ‘s return value, so we have to think of something else. Maybe we can somehow stub either log4js.getLogger()  or ?

Normally, I use sinon to create spies, stubs and mocks. With sinon, you can replace object methods or even the objects themselves.

As far as I know, it is not possible to modify the logger  object inside foo.js , because foo.spec.js  doesn’t have access to the scope of foo.js . We could add the logger  object to the foo.js  exports, but that doesn’t seem to be a very elegant solution. I’d rather not modify foo.js  itself.

Let’s see if we can stub getLogger() :

Does it work?

Yes it does!

However, this method relies on being able to stub log4js.getLogger()  before foo.js  is required. What happens if we require foo.js  before stubbing?

Unfortunately, this fails:

The reason that this fails, is that node.js uses a module cache. The first time a module is required, it is loaded; any followup require()  calls simply return the loaded module from node.js’s module cache.

This makes the test very fragile. If any other module requires foo.js  before this test is run, the logger  object inside foo.js  has already been created before the getLogger()  stub can be used.

What else is there to try?

We could add an appender to log4js  that captures any logged lines for verification afterward. Since there did not seem to be such an appender yet, I decided to create one.

This is how to use it:

There we go, a robust, working test.

The API of log4js-test-appender  is not very elegant yet, so if you have any suggestions for improvement, feel free to comment or create a merge request! And if you have an alternative suggestion to test log4js  log statements, I’m all ears.

This entry was posted in JavaScript, node.js, software development and tagged , , , , , , , , , , , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published.