• I paired with Josh Price wrote the javascript code below, just before that we noticed something abnormal about event handling and wanted to find out what happened.

    Just paste the code below into Firebug console of Firefox, run it, do something triggering events in page and watch the log printed out.

    Please note that this requires jQuery.

    var counter = 0;
    $("*").each(function() {
      var events = $(this).data('events');
      if(events) {
        $.each(events, function(type, handlers) {
          $.each(handlers, function(i, handler){
            handlers[i] = function(){
              handler.apply(this, arguments);
              console.log(++counter, type);
            };
          });
        });
      }
    });
    

     
    You can add more logging per your need, e.g. the time used for each handler call.

     

  • Here is the way we used today checking the quality of client side javascript code.

    Launch Firefox, access the site under developing, open Firebug console and run the scripts below:

     for(var property in window){
         console.log(property);
     }
    

     
    We get a list of properties directly defined in window instance, which is the place where all global functions and variables exist.

    Filter out the build in properties and the ones introduced by the external libs, like jQuery, Prototype, and we get all the global functions and variables defined by the team.

    Then ask:

    • Do we have too many of them and is it a sign of lacking encapsulation?
       
    • Are all of them worth being introduced with global accessibility?

     
    We really got some clues of refactoring, cool!

    The key is that try object oriented javascript before the plain global functions and variables run out of control.

     

  • 这是一个基于JSF的WEB应用,被测的场景是编辑一个巨大的表单,然后进行预览操作,最后再回到编辑页面,验证各个字段是否和以前的一样,据此间接检验各个页面元素与后台Bean的绑定是否正确。

    以前的测试不是人读的

    这是之前实现这一测试的代码片段:

    @Test
    public void createFullRequest_priview_backEditing_checkData(){
    goToCreationPage();
    browser.click(ADD_APPOINTMENT);
    browser.click("lorryTrucking1");
    browser.select("containerSizeType1_1", "label=20' Platform");
    typeAndBlur("containerQuantity1_1", "1");
    browser.select("cargoPackageType1_1", "label=Bar");

    ......

  • 最近的一个Web项目大部分的逻辑都是客户端页面逻辑,主要是通过Javascript实现的,如何进行高覆盖率的单元测试是我们面临的一个问题。

    分 析一下,有两种逻辑需要测试,一个是与服务器交互的页面操作,比如提交表单后跳转到另一个页面,这很适合写Selenium测试。这里关注的是另外一种, 即客户端页面逻辑,它与服务器没有交互,比如页面Dom元素的联动变化和数据校验逻辑等,这部分当然也可以写Selenium来测,而且由于不与服务器打 交道,组织得当的话速度也很快。但此时Selenium测试与代码实现的反馈距离太远,不方便组织细粒度的测试,更重要的是写这个测试对 Javascript代码的设计没什么帮助,因为再烂的Javascript实现可以方便地写出Selenium测试。

    对于客户端页面逻辑,我们尝试使用Jsunit进行测试。对于没有Dom操作的纯Javascript函数,测试很容易。对于有一定复杂度并有Dom操作的逻辑,我们将他们封装成Javascript对象并用Jsunit测试它。

    一个具体的例子

    上图是页面的一部分......