vendredi 16 septembre 2016

Unittesting in Karma : Keypress inside a text Input

Have a simple html text input:

<html>
<body>
    <input id="inputstring" type="text"  onkeypress="testcharacter" onKeyUp="testcharacter ">
    <div id ="result"></div>
    <script type="text/javascript" src="javascriptfile.js"></script>
    <script>testcharacter .init();</script>
</body>
</html>

Would like to be able to run a unittest on each keypress that occurs inside this text input and check it against a particular key. Javascript file is:

'use strict';

window.testcharacter = window.testcharacter || {};
    (function() {
    var testcharacter = function(k){
        var s = document.getElementById('inputstring').value
        if(s!=null||s.trim()!=""){
            if(k==65){
               document.getElementById('result').innerHTML = 'You pressed A'
            }
            if(s.length==0)
            { document.getElementById('result').innerHTML = ''}
        }
    }
window.testcharacter.init = function(){
    document.getElementById('inputstring').addEventListener('keyup', testcharacter );
    document.getElementById('inputstring').addEventListener('keypress', testcharacter );
};
  })();

A portion of my test file, concerning this portion I've got:

     it('should display character count with each keypress', function(){

            var triggerKeyDown = function(element,keycode){

                var e = jQuery.Event("testcharacter");
                e.which = keycode;
                $(element).trigger(e)
                var ee = jQuery.Event("keyup")
                ee.which = keycode + 1;
                $(element).trigger(ee)

                r = document.getElementById('inputstring').value

expect(document.getElementById('result').innerHTML).toBe(expected);
expect(document.getElementById('inputstring').innerHTML).toBe(expected);
            };
            triggerKeyDown('inputstring','65')

        });

Right now, the keypress and keyup don't seem to persist to the inputbox,(I can easily set the value using: document.getElementById('inputstring').value = 'A' which passes other portions of the tests, but not the keypresses) although I can see that the events are firing:

Testing of values:

ALERT: <input id="inputstring" type="text">   // captured 'inputstring'
ALERT: ''   // captured value of 'inputstring'.value and 'result'.innerHTML
ALERT: 65    // e.which value
ALERT: {type: 'keypress', timeStamp: 1474058737895, jQuery31006431827041498093: true, which: 65}   // event created

Not sure how to: (1) fire off keypress/keyup events in Jasmine (2) apply those events to the specific html element.value So I can test those values. I would like each keypress/keyup to be tested.

Aucun commentaire:

Enregistrer un commentaire