Skip to content

Instantly share code, notes, and snippets.

@ty4z2008
Created April 16, 2020 02:42
Show Gist options
  • Save ty4z2008/740161399c48c4f3507b637400a1a853 to your computer and use it in GitHub Desktop.
Save ty4z2008/740161399c48c4f3507b637400a1a853 to your computer and use it in GitHub Desktop.
use js simulate click and input in react or vue.
/**simluate click in react */
function simulateClick(element) {
if (element instanceof jQuery) {
element = element[0]
}
const mouseClickEvents = ['mousedown', 'click', 'mouseup']
console.log('[spirit] simulate click:', element)
mouseClickEvents.forEach(mouseEventType =>
element.dispatchEvent(
new MouseEvent(mouseEventType, {
view: window,
bubbles: true,
cancelable: true,
buttons: 1
})
)
)
}
/**simulate input in react */
function simulateInput(element, val) {
if (element instanceof jQuery) {
element = element[0]
}
let input = element
let lastValue = input.value
input.value = val
let event = new Event('input', {
bubbles: true
})
let keyPress = new KeyboardEvent('keyup', {
bubbles: true,
key: 'enter'
})
// hack React15
event.simulated = true
// hack React16
let tracker = input._valueTracker
if (tracker) {
tracker.setValue(lastValue)
}
input.dispatchEvent(event)
input.dispatchEvent(keyPress)
}
@ty4z2008
Copy link
Author

Useage:
simulateClick($("#app"))
simulateInput($("#app"),'value')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment