Module: Decidim::FrontEndFileTestHelpers

Defined in:
lib/decidim/dev/test/rspec_support/helpers.rb

Instance Method Summary collapse

Instance Method Details

#add_file(filename, target_selector, event) ⇒ Object



152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
# File 'lib/decidim/dev/test/rspec_support/helpers.rb', line 152

def add_file(filename, target_selector, event)
  file = file_to_frontend(filename)

  page.execute_script(
    <<~JS
      var dataUrl = "#{file[:data_url]}";
      fetch(dataUrl).then(function(res) { return res.arrayBuffer(); }).then(function (buffer) {
        var file = new File([buffer], "#{filename}", { type: "#{file[:mime_type]}" });
        var dropzone = document.querySelector("#{target_selector}");

        var dt = new DataTransfer();
        dt.items.add(file);

        if ("#{event}" === "drop") {
          var ev = new Event("drop");
          ev.dataTransfer = dt;
          dropzone.dispatchEvent(ev);
        } else {
          // Simulates selecting the file through the browser's file selector
          var input = dropzone.querySelector("input[type='file']");
          input.files = dt.files;
          input.dispatchEvent(new Event("change", { bubbles: true }));
        }
      });
    JS
  )

  # Wait for the file to be uploaded
  within "[data-dropzone-items]" do
    expect(page).to have_content(filename)
  end
end

#file_to_frontend(filename) ⇒ Object



140
141
142
143
144
145
146
147
148
149
150
# File 'lib/decidim/dev/test/rspec_support/helpers.rb', line 140

def file_to_frontend(filename)
  filepath = Decidim::Dev.asset(filename)
  mime = MiniMime.lookup_by_filename(filepath).content_type
  encoded = Base64.encode64(File.read(filepath))

  {
    filename:,
    data_url: "data:application/octet-binary;base64,#{encoded.gsub("\n", "")}",
    mime_type: mime
  }
end

#paste_file(filename, target_selector) ⇒ Object



185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
# File 'lib/decidim/dev/test/rspec_support/helpers.rb', line 185

def paste_file(filename, target_selector)
  file = file_to_frontend(filename)

  page.execute_script(
    <<~JS
      var dataUrl = "#{file[:data_url]}";
      fetch(dataUrl).then(function(res) { return res.arrayBuffer(); }).then(function (buffer) {
        var file = new File([buffer], "#{filename}", { type: "#{file[:mime_type]}" });

        var dt = new DataTransfer();
        dt.items.add(file);

        var element = document.querySelector("#{target_selector}");
        element.dispatchEvent(new ClipboardEvent("paste", { clipboardData: dt }));
      });
    JS
  )

  # Wait for the file to be uploaded
  sleep 1
end