Skip to content

Commit

Permalink
修复 模拟 input 不能触发 React 16 change 事件的问题
Browse files Browse the repository at this point in the history
  • Loading branch information
meowtec committed Apr 10, 2018
1 parent 6a2bbc7 commit 2ba8105
Showing 1 changed file with 14 additions and 20 deletions.
34 changes: 14 additions & 20 deletions lib/helper.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ const DataHubClient = require('datahub-nodejs-sdk');

const datahubClient = new DataHubClient();

const safeQuote = string => JSON.stringify(String(string))

const extendsMixIn = wd => {
wd.addPromiseChainMethod('initWindow', function(options = {}) {
return this
Expand Down Expand Up @@ -197,36 +199,28 @@ const extendsMixIn = wd => {

wd.addPromiseChainMethod('formatInput', function(cssSelector, string) {
const uuid = Date.now();
const input = `document.querySelector('${cssSelector}')`;
const eventHandle = `
var event_${uuid} = document.createEvent('Event');
event_${uuid}.initEvent('input', true, true);
_element_${uuid}.dispatchEvent(event_${uuid});
`;
const list = Array.prototype.slice.call(string);

if (!list.length) {
return this;
}
let value = list[0];

if (list.length === 1) {
const script = `
var _element_${uuid} = ${input};
_element_${uuid}.value='${value}';
${eventHandle}
`;
return this
.execute(script)
.sleep(100);
}
let value = '';

return Promise.reduce(list, (i, item) => {
value += item;
const script = `
var _element_${uuid} = ${input};
_element_${uuid}.value='${value}';
${eventHandle}
(function() {
var element = document.querySelector('${cssSelector}');
var setValue = Object.getOwnPropertyDescriptor(
window.HTMLInputElement.prototype,
'value'
).set;
setValue.call(element, ${safeQuote(value)});
var event = document.createEvent('Event');
event.initEvent('input', true, true);
element.dispatchEvent(event);
})()
`;
return this
.execute(script)
Expand Down

0 comments on commit 2ba8105

Please sign in to comment.