我对Jasmine有点困难。我正在使用Grunt的grunt-contrib-jasmine
插件通过PhantomJS自动化测试。我有already successfully loaded jQuery所以我没有遇到任何问题。主要问题是,当测试运行时,我无法让计数器倒计时。这是base.js
,计数器运行的脚本:
$(document).ready(function()
{
"use strict";
$('.text').keyup(function()
{
$('.count').text(60 - $(this).val().length);
});
});
其中.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');
});
答案 0 :(得分: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');
});
});