使用Phantomjs模拟程序按钮单击并使用Jasmine进行测试

时间:2013-03-26 07:45:47

标签: jquery bdd jasmine phantomjs

使用phantomjs-jasmine进行简单测试

//example_spec.js
describe("Click button", function() {
  it ("should be become 3", function() {
      var i = 0;
      var button_element = $('#button');
      console.log(button_element.text());
      while(i < 3 ) {
          button_element[0].click();
      console.log($('#counter').text());
        i ++;
      }
      console.log($('#counter').text());
    expect($('#counter').text()).toEqual('3');
  });

});



//example.js
var main = function() {
    var button = document.getElementById('button');

    button.addEventListener('click', function(){
        var count = document.getElementById('counter');
        count.innerText = parseInt(count.innerText) + 1;
    });
}
window.addEventListener('load', main);




window.addEventListener('load', main);

//index.html
....
<p id='counter'>0</p>
<button id='button'></button>
....

测试结果真的很奇怪

hantomjs lib/run_jasmine_test.coffee spec/TestRunner.html
Starting...
0
0
0

Click button : should be become 3
Error: Expected '1' to equal '3'.

Finished
-----------------
1 spec, 1 failure in 0.033s.

ConsoleReporter finished

我的代码中有些东西一定是错的,有什么想法吗?


//示例-更新完毕的jquery-version.js

var main = function() {
    var button = $('#button');

    $('#button').on('click', function(){
        $('#counter').text(parseInt($('#counter').text()) + 1);
    })

}

1 个答案:

答案 0 :(得分:2)

您确定PhantomJS支持innerText()吗? 如果您在Mozilla上尝试使用相同的代码段,则无法使用textContent()

尝试使用跨浏览器的jQuery's text() method instead

更新:innerText()是IE特定的方法,因此您必须使用textContent。如需进一步参考,请参阅this MDN's page