使用karma和qUnit对按钮单击进行简单的UI测试

时间:2013-11-29 19:20:00

标签: qunit karma-runner

我已经弄清楚如何使用karma测试运行器测试我的代码,但我无法弄清楚如何在网页上测试UI功能。

我有一个简单的计算器程序(calculator.js):

window.onload = function () {

    var okResult = /^.*(\+|\*|-|÷)\d$|^\d$|^.*\d((\+|\*|-|÷)|\d)$/,
        i, tds = document.getElementsByTagName("td");

    var setResult = function (t) {
        document.getElementsByTagName("th")[0].innerHTML = t;
    };

    var appendResult = function (t) {
        document.getElementsByTagName("th")[0].innerHTML += t;
    };

    var getResult = function () {
        return document.getElementsByTagName("th")[0].innerHTML;
    };

    for (i = 0; i < tds.length; i++) {

        tds[i].onclick = function () {

            var r;

            if (this.innerHTML == '=') {
                setResult(eval(getResult().replace(/÷+?/g, '/')));
            } else if (this.innerHTML == 'clr') {
                setResult("0");
            } else if (getResult() == '0') {
                setResult(this.innerHTML);
            } else {
                appendResult(this.innerHTML);
            }

            if (!okResult.test(getResult())) {
                r = getResult();
                setResult(r.substring(0, r.length - 1));
            }
        };
    }

};

使用HTML DOM中的这个简单表格(calculator / index.html):

<table>
    <tr>
        <th id="results" colspan="4">0</th>
    </tr>
    <tr>
        <td colspan="3">&nbsp;</td>
        <td>clr</td>
    </tr>
    <tr>
        <td>7</td>
        <td>8</td>
        <td>9</td>
        <td>&divide;</td>
    </tr>
    <tr>
        <td>4</td>
        <td>5</td>
        <td>6</td>
        <td>*</td>
    </tr>
    <tr>
        <td>1</td>
        <td>2</td>
        <td>3</td>
        <td>-</td>
    </tr>
    <tr>
        <td>.</td>
        <td>0</td>
        <td>=</td>
        <td>+</td>
    </tr>
</table>

我想通过触发DOM中找到的单元格上的点击事件来测试它。例如(calculator-spec.js):

test("Calculator initially displays 0", function () {
    equal( $('td#results').text(), "0", "Initial display is 0" );
});

test("Calculator can add numbers", function () {

    $('td:contains("1")').trigger('click');
    $('td:contains("+")').trigger('click');
    $('td:contains("1")').trigger('click');
    $('td:contains("=")').trigger('click');

    equal( $('td#results').text(), "2", "Initial display is 0" );

});

我正在尝试使用karma自动化测试,并且在我的karma.conf.js文件中我有:

//要使用的框架     框架:['qunit'],

// list of files / patterns to load in the browser
files: [
    'http://code.jquery.com/jquery-1.10.2.min.js',
    '**/Examples/Calculator/Complete/calculator.js',
    'test/calculator/calculator-spec.js',
    {pattern: '**/Examples/Calculator/Complete/index.html', watched: false, included: false, served: true}
],

如何使用业力执行UI测试。如何模拟鼠标和键盘事件并使用qUnit或jasmine检查生成的DOM?

1 个答案:

答案 0 :(得分:2)

我必须使用DOM元素点击方法:

$('td:contains("1")')[0].click();