2017-03-28 59 views
5

我正在用e2etesting我的應用程序使用nightwatch。其中一個測試失敗,因爲它無法滾動到正在測試的元素,我懷疑。問題是否需要滾動或者是否有另一種方式來執行?這是我測試的元素:如何使用Nightwatch滾動到元素?

return this.waitForElementVisible('#myElement', 4000) //wait for it to be visible 
     .assert.visible('#myElement') 
     .click('#myElement') 

的元素是在頁面的頂部,但TestRunner的已滾動了一下這個頁面,它是不是在截圖中可見。 如何滾動到此元素?或者:我如何測試這個元素?

回答

2

在守夜有一個本地方法來獲取元素。 (在一般要素應始終滾動到從nightwatch /硒的看法,但如果你想這樣做手工,你可以使用getLocationInView()

return this.getLocationInView('#myElement') 
    .assert.visible('#myElement') 
    .click('#myElement') 

Nightwatch還支持直接通過webdriver的協議使用moveTo()這樣做沒有任何抽象。在這種情況下,它看起來更像是:

const self = this; 
return this.api.element('#myElement', (res) => { 
    self.api.moveTo(res.value.ELEMENT, 0, 0() => { 
    self.assert.visible('#myElement'); 
    self.click('#myElement'); 
    }) 
}); 

(這只是從我的頭頂上寫的,希望我沒有犯錯)

但是可能你的情況幫是改變seleniums在像config元素滾動行爲:

firefox: { 
    desiredCapabilities: { 
    browserName: 'firefox', 
    javascriptEnabled: true, 
    acceptSslCerts: true, 
    elementScrollBehavior: 1 
    } 
} 

默認值爲0 - >元素被滾動到頁面頂部

elementScrollBavior 1 - >元素被滾動到的底部

+1

執行這個JavaScript這將是有益的一提的是本機方法是http://nightwatchjs.org/api/moveTo.html –

+0

@MikeDavlantes感謝您的輸入。我試圖擴展我的描述,希望我記得如何在夜間正確使用它:'D – TheBay0r

4

記住:

.execute()注入JavaScript代碼段到頁面爲在當前選擇的幀的上下文 執行。假定執行的 腳本是同步的,並且將評估 腳本的結果返回給客戶端。

Window.scrollTo()滾動到一組特定的 文檔中的座標。

你的測試將是這樣的:

module.exports = { 
    'your-test': function (browser) { 
     browser 
      .url("http://example.com") 
      .waitForElementPresent('body', 2000, "Be sure that the page is loaded") 
      .execute('scrollTo(x, y)') 
      .yourFirstAssertionHere() 
      .yourSecondAssertionHere() 
      ... 
      .yourLastAssertionHere() 
      .end() 
    } 
}; 
  • 如果你知道與ID myElement元素是在頁面的頂部,你可以僅僅通過0改變xy(只以確保您將滾動到頁面的頂部)。

  • 如果你需要得到的xy的精確值,可以使用:getLocationInView()這樣的:

    module.exports = { 'your-test': function (browser) { browser .url("http://example.com") .waitForElementPresent('body', 2000, "Be sure that the page is loaded") .getLocationInView("#myElement", function(result) { //The x value will be: result.value.x //The y value will be: result.value.y }); } }

    .getLocationInView():屏幕 上確定元素的位置一旦滾動到視圖中... 返回頁面元素的X和Y座標 。

希望這有助於你。

2

您可以executedocument.querySelector({{ACTUAL_SELECTOR}}).scrollIntoView();

+0

'scrollIntoView()'在所有主流瀏覽器中都是兼容的。 https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView#Browser_compatibility – lasec0203