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:

global.ko = require('../../Website/Scripts/knockout-3.4.0.js');

var MyViewModel = require('../../Website/Scripts/myViewModel.js').MyViewModel;

describe('MyViewModel', function() {
    var viewModel;
        viewModel = new MyViewModel();

    describe('...', function() {
        /* And so on */

3 thoughts on “Testing Knockout with Mocha and without a browser

Leave a Reply

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

You may use these HTML tags and attributes:

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.