2014-11-25 69 views
6

我在第三天與量角器一起工作,並且我經常觸碰金磚四壁,等待頁面加載和元素出現。特別是這個測試案例變得越來越醜陋,我想解決這些問題,而不必依賴睡眠。等待元素更改其值(文本)

我目前「AngularJS的土地之外」

it('it should reflect in both the field and the title when the personnel name is changed', function() { 
    var inputField, personnelHeader, personnelName; 
    personnelName = element(By.css(".overlay.editnameoverlay")).click(); 
    personnelHeader = element(By.id("personnel_name_header")); 
    inputField = element(By.css("input[name='newvalue']")); 
    inputField.clear(); 
    inputField.sendKeys("Test 123"); 
    element(By.css("input[name='ok_button']")).click(); 
    // browser.driver.sleep(2000); This test only works with this sleep added 
    browser.wait(function() { 
    console.log("Waiting for header to change..."); 
    return personnelHeader.getText().then(function(text) { 
     return text === "Test 123"; 
    }); 
    }, 5000); 
    return expect(personnelHeader.getText()).toBe(personnelName.getText()); 
}); 

所以測試在這裏輸入字段更名。提交它並等待更改反映在模態的標題中。問題是,如果沒有browser.driver.sleep(2000年)我得到一個錯誤說

Stacktrace: 
    StaleElementReferenceError: stale element reference: element is not attached to the page document 

我如何去在這種特殊情況下解決這個?

回答

6

當您使用量角器測試非角度頁面時,您自己就等待元素準備好進行交互。

StaleElementReferenceError可能是最無用的硒錯誤,當它發生的元素得到了從DOM刪除,但用量角器開始,甚至tried to convince應該自動重試量角器邊時仍緩存不知怎麼的,我也suffered這個問題。

對我來說,解決辦法是始終明確等因素的頁面上使用出現custom functionwaitReady()browser.wait的要素準備,即:等待元素是可用於交互:

expect($('#login_field').waitReady()).toBeTruthy(); 

首先這個片段在你的代碼集成:https://gist.github.com/elgalu/2939aad2b2e31418c1bb

不僅定製waitReady()等待元素,但它也吞下任何無關的無用webdriver的錯誤,如StaleElementReferenceError並會簡單地重試,直至找到元素或它會超時。

所以waitReady()clear()sendKeys()click()之前相互作用,即之前的每個元素...

// TODO: Move to Page Objects module 
var personnelNameElm = $(".overlay.editnameoverlay"); 
var personnelHeaderElm = $("#personnel_name_header"); 
var inputFieldElm = $("input[name='newvalue']"); 
var okBtnElm = $("input[name='ok_button']"); 

it('it should reflect in both the field and the title when the ' + 
    'personnel name is changed', function() { 

    expect(personnelNameElm.waitReady()).toBeTruthy(); 
    personnelNameElm.click(); 
    expect(inputFieldElm.waitReady()).toBeTruthy(); 
    inputFieldElm.clear().sendKeys("Test 123"); 
    expect(okBtnElm.waitReady()).toBeTruthy(); 
    okBtnElm.click(); 

    browser.wait(function() { 
    console.log("Waiting for header to change..."); 
    // Using waitReady() before getText() avoids Stale element errors 
    return personnelHeaderElm.waitReady().then(function() { 
     return personnelHeaderElm.getText().then(function(text) { 
     return text === "Test 123"; 
     }); 
    }); 
    }, 5000); 

    expect(personnelHeaderElm.getText()).toEqual(personnelNameElm.getText()); 
}); 
8

從文檔Expect Conditions

var EC = protractor.ExpectedConditions; 
// Waits for the element with id 'abc' to contain the text 'foo'. 
browser.wait(EC.textToBePresentInElement($('#abc'), 'foo'), 5000);