Knockout-Validation - Unit Testing Helper

Template for writing QUnit tests for Knockout Validation library.

by Cristian Trifan

HTML

<link rel="stylesheet" href="//code.jquery.com/qunit/qunit-1.16.0.css">
<script src="//code.jquery.com/qunit/qunit-1.16.0.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-debug.js"></script>
<script src="//rawgit.com/Knockout-Contrib/Knockout-Validation/master/Dist/knockout.validation.js"></script>
<div id="qunit"></div>

<!-- This is where tests will inject their HTML -->
<div id="testContainer"></div>

JavaScript

'use strict';

//------------------------------------------------------------------------------
// Helper methods
//
var applyTestBindings = function (vm) { ko.applyBindingsWithValidation(vm, $('#testContainer')[0]); };
var addTestHtml = function(html){ $('#testContainer').html(html); };
//------------------------------------------------------------------------------

module('UI Tests', {
    beforeEach: function () {
    },
    afterEach: function () {
        ko.cleanNode($('#testContainer')[0]);
        $('#testContainer').empty();
        ko.validation.reset();
    }
});

// Example
test('Inserting Messages Works', function () {
    addTestHtml('<input id="myTestInput" data-bind="value: firstName" type="text" />');

    var vm = {
        firstName: ko.observable('').extend({ required: true })
    };

    applyTestBindings(vm);

    var $testInput = $('#myTestInput');

    $testInput.val('a'); //set it
    $testInput.change(); //trigger change event

    $testInput.val(''); //set it
    $testInput.change(); //trigger change event

    var isValid = vm.firstName.isValid();

    ok(!isValid, 'First Name is NOT Valid');

    var msg = $testInput.siblings().first().text();

    equal(msg, 'This field is required.', msg);
});