1

使用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

我的代码中一定有问题,知道吗?


//example-updated-jquery-version.js

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

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

}
4

1 回答 1

2

您确定innerText()PhantomJS 支持吗?如果您在 Mozilla 上尝试相同的代码段,它将无法正常工作,因为您应该使用textContent().

尝试改用jQuery的text()方法,它是跨浏览器的。

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

于 2013-03-26T07:57:44.273 回答