定義區塊

有時定義頁面的區塊會很有用。區塊會執行兩件事

  • 在頁面下提供命名空間層級
  • 提供元素層級的巢狀結構,以便在區塊內定義的任何元素都是 DOM 中其父區塊的子系

宣告區塊

您可以使用 sections 屬性建立區塊

nightwatch/pages/samplePage.js
module.exports = {
  sections: {
    menu: {
      selector: '#gb',
      elements: {
        mail: {
          selector: 'a[href*="mail"]'
        },
        images: {
          selector: 'a[href*="imghp"]'
        }
      }
    }
  }
};

在測試中使用區塊

您的測試會如下使用它

tests/sampleTest.js
describe('sample test with page objects', function() {
  it('Test', function (browser) {
    var google = browser.page.google();
    google.expect.section('@menu').to.be.visible;
    
var menuSection = google.section.menu; menuSection.expect.element('@mail').to.be.visible; menuSection.expect.element('@images').to.be.visible;
menuSection.click('@mail');
browser.end(); }); });

請注意,區塊上的每個指令和斷言 (除了 expect 斷言) 都會傳回該區塊以進行鏈結。如果需要,您可以將區塊巢狀置於其他區塊下,以建立複雜的 DOM 結構。

巢狀頁面對象區塊

nightwatch/pages/samplePage.js
module.exports = {
  sections: {
    menu: {
      selector: '#gb',
      elements: {
        mail: {
          selector: 'a[href*="mail"]'
        },
        images: {
          selector: 'a[href*="imghp"]'
        }
      },
      sections: {
        apps: {
          selector: 'div.gb_pc',
          elements: {
            myAccount: {
              selector: '#gb192'
            },
            googlePlus: {
              selector: '#gb119'
            }
          }
        }
      }
    }
  }
};

在您的測試中使用巢狀區塊非常簡單
tests/sampleTest.js
describe('sample test with page objects', function() {
  it('Test', function (browser) {
    var google = browser.page.google();
    google.expect.section('@menu').to.be.visible;
    
var menuSection = google.section.menu; var appSection = menuSection.section.apps; menuSection.click('@appSection');
appSection.expect.element('@myAccount').to.be.visible; appSection.expect.element('@googlePlus').to.be.visible;
browser.end(); }); });