nightwatch + selenium 瀏覽器自動化測試 教程(二)
阿新 • • 發佈:2018-12-19
上一篇已經講述瞭如何搭建環境,這一片主要針對語法進行
目錄
測試案例
module.exports = { 'Demo test Google' : function (browser) { browser .url('http://www.google.com') .waitForElementVisible('body', 1000) .setValue('input[type=text]', 'nightwatch') .waitForElementVisible('button[name=btnG]', 1000) .click('button[name=btnG]') .pause(1000) .assert.containsText('#main', 'Night Watch') .end(); } };
這裡提示下,每個測試最好在結尾執行end(), 這樣nigthwatch才會關閉selenium session
上述為nightwatch的一個案例,nigthwatch預設使用css選擇器作為定位元素。
在nightwatch裡,source目錄下的每個js檔案為一個測試類,例如如下工程中有兩個測試檔案,則為兩個類
一個檔案作為一個測試類,一個測試類可以有多個步驟
module.exports = { 'step one' : function (browser) { browser .url('http://www.google.com') .waitForElementVisible('body', 1000) .setValue('input[type=text]', 'nightwatch') .waitForElementVisible('button[name=btnG]', 1000) }, 'step two' : function (browser) { browser .click('button[name=btnG]') .pause(1000) .assert.containsText('#main', 'Night Watch') .end(); } };
也可以如下表示
this.demoTestGoogle = function (browser) { browser .url('http://www.google.com') .waitForElementVisible('body', 1000) .setValue('input[type=text]', 'nightwatch') .waitForElementVisible('button[name=btnG]', 1000) .click('button[name=btnG]') .pause(1000) .assert.containsText('#main', 'The Night Watch') .end(); };
Using XPath選擇器
預設nightwatch是使用css選擇器進行元素定位的,在測試類中使用useXpath()函式進行切換,例如
module.exports = {
'get csdn access time' : function (browser) {
browser
.url('https://blog.csdn.net/Viogs')
.waitForElementVisible('body', 1000)
.useXpath() //使用xpath函式切換選擇器為xpath
.getAttribute('//*[@id="asideProfile"]/div[3]/dl[2]/dd', "title", function (res) {
console.log("訪問次數為"+res.value); //獲取部落格的訪問次數,並且打印出來
})
browser.end()
}
}