0

我对茉莉花有点困难。我正在使用grunt-contrib-jasmine带有 Grunt 的插件通过 PhantomJS 进行自动化测试。我已经成功加载了 jQuery,所以我对此没有任何问题。主要问题是当测试运行时我无法让我的计数器倒计时。这是base.js计数器运行的脚本:

$(document).ready(function()
{
    "use strict";
    $('.text').keyup(function()
    {
        $('.count').text(60 - $(this).val().length);
    });
});

where.text是输入字段,并且.count是计数器所在的跨度。这是该文件的规范:

describe("Main JS file", function() {

    "use strict";

    var $text, $count;

    beforeEach(function() {
        $count = $('<span class="count">60</span>');
        $text = $('<input type="text" maxlength="60" class="text">');
    });

    it("displays a count of the characters in the text box", function() {
        $text.val('Hello, World!');
        $text.trigger('keyup');
        expect($count.text()).toEqual(47);
    });

});

这是中的配置Gruntfile.js

jasmine: {
    tests: {
        src: ['assets/js/base.js'],
        options: {
            specs: 'spec/base.js',
            vendor: ['assets/js/jquery.js']
        }
    }
},

当我运行时,grunt jasmine我只收到此错误:

$ grunt jasmine
Running "jasmine:tests" (jasmine) task
Testing jasmine specs via phantom
x
Main JS file:: displays a count of the characters in the text box: failed
  Expected '60' to equal 47. (1)
1 spec in 0.001s.
>> 1 failures

非常感谢您对此的任何帮助。提前致谢。

更新:现在使用 jasmine-jquery,我可以看到事件已触发,但计数器文本仍未更新!

it("displays a count of the characters in the text box", function() {

    spyOnEvent($text, 'keyup');
    $text.val('Hello, World!');
    $text.keyup();
    expect('keyup').toHaveBeenTriggeredOn($text);
    expect($count).toHaveText('47');
});
4

1 回答 1

1

问题是您尝试在before函数中呈现元素之前绑定键事件。一种想法是重构您的代码,以便您可以在测试中运行绑定事件的函数。

function addKeyEvent(){
 $('.text').keyup(function()
    {
        $('.count').text(60 - $(this).val().length);
    });
}

$(document).ready(addKeyEvent);

在您的测试中,在创建元素后调用该函数:

describe("Main JS file", function() {

"use strict";

var $text, $count;

beforeEach(function() {
    $count = $('<span class="count">60</span>').appendTo('body');
    $text = $('<input type="text" maxlength="60" class="text">').appendTo('body');
    addKeyEvent()
});

it("displays a count of the characters in the text box", function() {
    $text.val('Hello, World!');
    $text.trigger('keyup');
    expect($count.text()).toEqual('47');
});

});
于 2013-08-05T11:10:27.750 回答