Home  >  Q&A  >  body text

Handle the case where there are no input elements in the DOM when selecting files using the Cypress method

<p>When clicking the upload button, use the method below to open the file browser. As far as I know, no element is added to the DOM unless you explicitly attach it to the DOM element. </p> <pre class="brush:js;toolbar:false;">const inputEl = document.createElement("input"); inputEl.type = "file"; inputEl.multiple = true; inputEl.click(); inputEl.onchange = (e) => { ... } </pre> <p>Is it possible to select files using this method in Cypress? <code>selectFile</code> requires the <code>input</code> element to be in the DOM and the link to follow it. Otherwise I will have to use hidden input elements. </p>
P粉697408921P粉697408921431 days ago438

reply all(1)I'll reply

  • P粉832490510

    P粉8324905102023-09-06 16:45:08

    solved. Can't do it in Cypress. I used an environment variable "DEVELOPMENT=1" to append the input element to the DOM, but only during testing.

    const inputEl = document.createElement("input");
    if (process.env.DEVELOPMENT) {
        document.getElementById("root").appendChild(inputEl);
    }
    inputEl.type = "file";
    inputEl.multiple = true;
    inputEl.click();
    inputEl.onchange = (e) => { ... }
    
    

    reply
    0
  • Cancelreply