Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

【React hack】在 React 中模拟触发输入 #17

Closed
z0ffy opened this issue Nov 11, 2024 · 0 comments
Closed

【React hack】在 React 中模拟触发输入 #17

z0ffy opened this issue Nov 11, 2024 · 0 comments

Comments

@z0ffy
Copy link
Owner

z0ffy commented Nov 11, 2024

在 React 中进行模拟触发输入

参考:facebook/react#11488

在自动化测试或在线调试React项目中,会遇到直接修改input的valut值UI变化,但是内部state并没有修改的情况。因此需要hack方法来解决:

let input = document.querySelector('xxx');
let lastValue = input.value;
input.value = 'xxx';
let event = new Event('input', {bubbles: true});
event.simulated = true;
let tracker = input._valueTracker;
if (tracker) {
  tracker.setValue(lastValue)
}
input.dispatchEvent(event);
const enterKeyEvent = new KeyboardEvent('keypress', {
  key: 'Enter',
  keyCode: 13,
  code: 'Enter',
  which: 13,
  bubbles: true,
});
input.dispatchEvent(enterKeyEvent);
const fileInput = document.querySelector('input[type="file"]');

async function simulateRemoteFileSelection(url) {
  const response = await fetch(url);
  const blob = await response.blob();

  const file = new File([blob], "file.mp4", {
    type: blob.type,
  });

  const dataTransfer = new DataTransfer();
  dataTransfer.items.add(file);

  fileInput.files = dataTransfer.files;

  const event = new Event('change', {bubbles: true});
  fileInput.dispatchEvent(event);
}

simulateRemoteFileSelection('xxxx');
@z0ffy z0ffy closed this as completed Nov 11, 2024
@z0ffy z0ffy added the react label Nov 22, 2024
@z0ffy z0ffy changed the title 【React hack】在React中模拟触发输入 【React hack】在 React 中模拟触发输入 Jan 1, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant