
Page Objects 預先定義一個頁面裡面的元素(element)、區塊(section)和命令(command),意即將一個網頁切分成許多個片段,然後利用物件把這些片段包裝起來使用,例如:將一個頁面區分為 header、footer 等,然後在測試程式中就用這樣的 header 或 footer 為單位操作 DOM element(點此複習 Page Objects)。
好處有二
接著來看如何使用 Sections 優化 Page Objects。
♡(´∀`)人(´∀`)♡
本系列文章皆使用這個專案,可以拉下來玩玩;有什麼問題都可以提出 issue。
Sections 可當成 Page Object 的切分單位,它為此網頁提供命名空間(namespacing),提供巢狀結構的起始位置,即最一開始的父層起點。Sections 對於抽象化複雜頁面的時候很有幫助。
使用方式如下,在定義 sections 的 selector 指定 CSS Selector,接著在底下繼續定義元素。
使用 Sections 撰寫 Page Objects。
module.exports = {
  url: 'http://find.ruten.com.tw/search/s000.php?enc=u&searchfrom=indexbar&k=Pusheen&t=0',
  commands: [findCommands],
  sections: {
    filter: {
      selector: '#side_filter',
      elements: {
        title: {
          selector: '.rt-filter-title'
        }
      }
    }
  }
};
在測試程式中使用 Sections
module.exports = {
  'Assert Filter Visible': function (client) {
    var findPage = client.page.findPage();
    findPage.navigate();
    findPage.expect.section('@filter').to.be.visible;
    var filterSection = findPage.section.filter;
    filterSection.expect.element('@title').to.be.visible;
    client.end();
  }
};

巢狀結構的應用範例如下,這裡定義一個 Section「menu」其中有兩個 Element「mail」和「images」,這個 Sections 之內還包有 Section「apps」,並且它也有兩個 Element「fb」和「gp」。
module.exports = {
  sections: {
    menu: {
      selector: '#menu',
      elements: {
        mail: {
          selector: '.mail'
        },
        images: {
          selector: '.images'
        }
      },
      sections: {
        apps: {
          selector: '.social-list',
          elements: {
            fb: {
              selector: '#fb'
            },
            googlePlus: {
              selector: '#gp'
            }
          }
        }
      }
    }
  }
};
在測試程式中使用巢狀的 Sections
'Test Social Account': function (client) {
  var findPage = client.page.findPage();
  findPage.navigate();
  findPage.expect.section('@menu').to.be.visible;
  var menuSection = findPage.section.menu;
  var appSection = menuSection.section.apps;
  menuSection.click('@appSection');
  appSection.expect.element('@fb').to.be.visible;
  appSection.expect.element('@googlePlus').to.be.visible;
  client.end();
}
Page Objects 的介紹就到此為止。
下一篇來看客製化指令(Custom Commands)。
網誌版。