使用QUnit测试项目是否具有某个类

时间:2016-04-12 14:02:26

标签: javascript jquery unit-testing input qunit

我已经创建了一个密码输入模块,其中包含几个正则表达式和一个列表,告诉用户要创建密码需要满足哪些要求,即提交表单。我正在为keyup上的每个需求列表项添加/删除一个类,具体取决于它是否满足要求。

我正在使用QUnit来测试这些元素是否获得了类。有任何想法吗?

Codepen: http://codepen.io/eplehans/pen/xVYMLp

HTML看起来大致如下:

<label for="password">Password input</label>
<input pattern="(?=^.{8,}$)((?=.*\d)|(?=.*\W+))(?![.\n])(?=.*[a-z]).*$" id="password" name="password" type="password">

<ul class="input-requirements-list">
    <li class="input-requirements-list__item" data-psw-req="8-chars">8 characters minimum</li>
    <li class="input-requirements-list__item" data-psw-req="1-special-char">1 special character</li>
</ul>`

JS看起来大致如下:

function passwordRegEx($input, $list) {
    var currentVal;
    var affirmativeClass = 'affirmative';

    function okCheck($el, affirmative) {
        if (affirmative === true) {
        $el.addClass(affirmativeClass);
        } else {
            $el.removeClass(affirmativeClass);
        }
    }

    //Requirements as shown in requirements list underneath password input
    var $charChecker = $list.find('[data-psw-req="8-chars"]'),
    $specialCharChecker = $list.find('[data-psw-req="1-special-char"]');

    $input.keyup(function() {
        currentVal = $input.val();

        //More than 8 characters
        if (currentVal.length >= 8) {
           okCheck($charChecker, true);
        } else {
        okCheck($charChecker, false);
        }

        //Special character match
        if (currentVal.match(/[-!$%^&*()@øæåØÆÅ_+|~=`{}\[\]:";'<>?,.\/]/)) {
           okCheck($specialCharChecker, true);
        } else {
          okCheck($specialCharChecker, false);
        }
    });
}

QUnit测试如下所示:

var $passwordInput = $('#password'),
    affirmativeClass = 'affirmative';
var $reqItem1 = $('li[data-psw-req="8-chars"]'),
    reqItem2 = $('li[data-psw-req="1-special-char]');

QUnit.test("Expect [data-psw-req=8-chars] to have class when requirements are met", function(assert) {
    $passwordInput.val('123456789dddddd');
    ok($reqItem1.hasClass(affirmativeClass), true, "It has the class!");
});

1 个答案:

答案 0 :(得分:2)

您必须触发与写入时用户触发的事件相同的事件。在这里,我触发了keyup事件,就像用户在完成输入时一样。

http://codepen.io/tomkarachristos/pen/MyQxbQ

QUnit.test("Expect li[data-psw-req=8-chars] to have affirmative class when password input has 8 or more characters", function(assert) {

    $passwordInput.val('123456789dddddd');
    $passwordInput.keyup();
    ok($reqItem1.hasClass(affirmativeClass), true, "It has the class!");

});