Headless knockout viewmodel testing with mocha

两盒软妹~` 提交于 2019-12-03 06:50:32
Kato

This is a topic currently on my radar as well. I'll dump my findings here in the hopes that they might point you in the right direction.

The likely route I will attempt first will be PhantomJS. It's a headless WebKit browser, so it should have excellent DOM, JSON, HTML5, and CSS selectors support (it works with jQuery and qUnit, for example).

I chose this because it is used by knockout.js itself, which I discovered in the knockout.js repository, where there was a .travis.yml file and this comment:

I don't have any proof that this is going to work, but was encouraged by its use in knockout.js core. I also found this runner script for knockout/phantom that looks like a great launch point.

I've also found a few examples using Mocha and PhantomJS via node.js, including this lib extending grunt to run mocha inside Phantom, and this script showing how to run mocha inside PhantomJS. So that part is certain, at the very least.

Another solution noted in the knockoutjs archives, is to use knockout-node and JsDOM to create a workable DOM, but at first glance, this seemed too nebulous and likely to result in implementing your own test environment.

There is a slidedeck suggesting zombie.js would work with knockout/node/etc. But I can't find anything offering hard evidence, so I didn't like this route either.

Maybe this is because Knockout has changed (as the accepted answer is old), but today, I don't believe this is necessary (anymore). You can easily test a Knockout viewmodel. All I needed to do was set the global ko variable in my test:

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

After that, you can run your test as usual: instantiate your viewmodel, perform any operations on it and assert.

I've written a little more about it, but in essence, this works for me:

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 */
    });
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!