Solved, see answer below
I test a React app with selenium.
I need to change the value of an input field, which is linked to the state of the object. In short (relevant parts of the code), a change in this input allows it's value to be submited only if it is not empty:
# 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
}
},
The code works but I cannot find a way to test it because I cannot find any js manipulation which would update the input AND reflect in the state of the object. I tried the following solutions
# value update
self.selenium.execute_script("var input = document.querySelectorAll('input.myInput')[0]; form.value = 'New message!'");
The word 'New message!' actually appears in the input but does not update the state of the object. I then tried focusing on the input and triggering a keyup event, without success
# 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);
""")
I tried the same solution with jQuery as explained here (Is it possible to simulate key press events programmatically?), but it does not work either.
Any idea is very welcome. Thanks!