September 26, 2016

Testing Knockout with Mocha and without a browser

I’ve recently been adding Knockout to an ASP.NET MVC application. I would consider Knockout a previous-generation solution and would prefer to use a full-fledged SPA framework like Aurelia, but that’s a bit out of scope for the moment.

After introducing Knockout, I wanted to add unit tests on my viewmodels with Mocha. I had some trouble at first, and read quite some answers on StackOverflow that claimed you need a browser. Because you’d want to run the tests from a command line (e.g. via npm test) the headless browser PhantomJS comes to mind.

However, this all appears to be unnecessary, and testing Knockout viewmodels (not components!) works perfectly with Mocha. All you need to do is set the global ko variable.

This piece of code should clarify it:

Leave a Reply

Your email address will not be published. Required fields are marked *