2016-02-25 26 views
0

解決,請參閱下面陣營 - Selenium測試

答案,我測試應用程序做出反應硒。

我需要更改輸入字段的值,該字段鏈接到對象的狀態。總之(代碼的相關部分),在此輸入的改變使得它的價值將只有submited如果它不是空的:

# react object 

render: function(){ 

    <input ... onChange={this.handleTextChange} className="myInput" /> 

    <button onClick={this.handleSubmit}>Submit</button> 
}, 

handleTextChange: function(e) { 
    this.setState({text: e.target.value}); 
}, 

handleSubmit: function() { 
    if(this.state.text.length > 0) { 
    // relevant code that is never executed 
    // because although we change the value of the input, the state does not update 
    } 
}, 

代碼工作,但我不能找到一種方法來測試它,因爲我不能找到任何更新輸入AND並反映在對象狀態中的js操作。 我試過以下解決方案

# value update 
self.selenium.execute_script("var input = document.querySelectorAll('input.myInput')[0]; form.value = 'New message!'"); 

單詞'New message!'實際上出現在輸入中但不更新對象的狀態。 我又試圖專注於輸入和觸發keyup事件,但沒有成功

# try focus and keyUp 
# source https://stackoverflow.com/questions/596481/simulate-javascript-key-events 
self.selenium.execute_script(""" 
var form = document.querySelectorAll("input.messageFormInput")[0]; 
form.focus(); 
var keyboardEvent = document.createEvent("KeyboardEvent"); 
var initMethod = typeof keyboardEvent.initKeyboardEvent !== 'undefined' ? "initKeyboardEvent" : "initKeyEvent"; 
keyboardEvent[initMethod](
       "keydown", // event type : keydown, keyup, keypress 
       true, // bubbles 
       true, // cancelable 
       window, // viewArg: should be window 
       false, // ctrlKeyArg 
       false, // altKeyArg 
       false, // shiftKeyArg 
       false, // metaKeyArg 
       40, // keyCodeArg : unsigned long the virtual key code, else 0 
       0 // charCodeArgs : unsigned long the Unicode character associated with the depressed key, else 0 
); 
document.dispatchEvent(keyboardEvent); 
""") 

我試圖相同的解決方案使用jQuery這裏解釋(Is it possible to simulate key press events programmatically?),但它也不管用。

任何想法都非常受歡迎。謝謝!

+0

我只是好奇,如果你使用硒,爲什麼不只是像普通用戶那樣與頁面交互,而不是手動觸發事件。例如,爲什麼不模擬基於與dom元素的交互來觸發事件的用戶行爲? –

+1

嗨克里斯!我試過self.selenium.find_elements_by_class_name(「MyInput」)[0] .click()。問題是我不知道如何在輸入中實際寫入文本。 – Raphael

回答

1

我的壞,我不知道的

self.selenium.find_elements_by_class_name('myClass')[0].send_keys("hello") 

裏面居然解決了這個問題。感謝Chris Hawkes送我正確的方向。

+1

這個解決方案節省了我的一天。感謝發佈! –

+0

很高興幫助! – Raphael