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; beforeEach(function(){ viewModel = new MyViewModel(); }); describe('...', function() { /* And so on */ }); });
If you want to test the components and they can be tested without knockout I’d suggest moving the registration (which is the only part I can see now that depends on knockout) to another file and test only the component itself.
Thanks for your comment. Indeed, that could be a good road to go. But it would mean more files. Not that files cost anything, but I liked my Knockout viewmodel with eveeything necessary in one file.
I say liked because it’s been a long time since I worked with knockout. So I might do it differently today.
Also, if you’re using something from Knockout in your viewmodel, putting the register in a separate file might not be an option.
If you do in fact need knockout to be present you might also depend on the browser via Knockout (I don’t know knockout, so I’m not sure about this). In that case you are probably better of running using karma. (You can use mocha instead of jasmine with karma if you want).