How to use waitForFileChooser method in Puppeteer

Best JavaScript code snippet using puppeteer

Run Puppeteer automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

input.spec.js

Source: input.spec.js Github

copy
1/**
2 * Copyright 2017 Google Inc. All rights reserved.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *     http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17const path = require('path');
18
19const FILE_TO_UPLOAD = path.join(__dirname, '/assets/file-to-upload.txt');
20
21module.exports.addTests = function({testRunner, expect, puppeteer}) {
22  const {describe, xdescribe, fdescribe, describe_fails_ffox} = testRunner;
23  const {it, fit, xit, it_fails_ffox} = testRunner;
24  const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
25  describe('input', function() {
26    it('should upload the file', async({page, server}) => {
27      await page.goto(server.PREFIX + '/input/fileupload.html');
28      const filePath = path.relative(process.cwd(), FILE_TO_UPLOAD);
29      const input = await page.$('input');
30      await input.uploadFile(filePath);
31      expect(await page.evaluate(e => e.files[0].name, input)).toBe('file-to-upload.txt');
32      expect(await page.evaluate(e => {
33        const reader = new FileReader();
34        const promise = new Promise(fulfill => reader.onload = fulfill);
35        reader.readAsText(e.files[0]);
36        return promise.then(() => reader.result);
37      }, input)).toBe('contents of the file');
38    });
39  });
40
41  describe_fails_ffox('Page.waitForFileChooser', function() {
42    it('should work when file input is attached to DOM', async({page, server}) => {
43      await page.setContent(`<input type=file>`);
44      const [chooser] = await Promise.all([
45        page.waitForFileChooser(),
46        page.click('input'),
47      ]);
48      expect(chooser).toBeTruthy();
49    });
50    it('should work when file input is not attached to DOM', async({page, server}) => {
51      const [chooser] = await Promise.all([
52        page.waitForFileChooser(),
53        page.evaluate(() => {
54          const el = document.createElement('input');
55          el.type = 'file';
56          el.click();
57        }),
58      ]);
59      expect(chooser).toBeTruthy();
60    });
61    it('should respect timeout', async({page, server}) => {
62      let error = null;
63      await page.waitForFileChooser({timeout: 1}).catch(e => error = e);
64      expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
65    });
66    it('should respect default timeout when there is no custom timeout', async({page, server}) => {
67      page.setDefaultTimeout(1);
68      let error = null;
69      await page.waitForFileChooser().catch(e => error = e);
70      expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
71    });
72    it('should prioritize exact timeout over default timeout', async({page, server}) => {
73      page.setDefaultTimeout(0);
74      let error = null;
75      await page.waitForFileChooser({timeout: 1}).catch(e => error = e);
76      expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);
77    });
78    it('should work with no timeout', async({page, server}) => {
79      const [chooser] = await Promise.all([
80        page.waitForFileChooser({timeout: 0}),
81        page.evaluate(() => setTimeout(() => {
82          const el = document.createElement('input');
83          el.type = 'file';
84          el.click();
85        }, 50))
86      ]);
87      expect(chooser).toBeTruthy();
88    });
89    it('should return the same file chooser when there are many watchdogs simultaneously', async({page, server}) => {
90      await page.setContent(`<input type=file>`);
91      const [fileChooser1, fileChooser2] = await Promise.all([
92        page.waitForFileChooser(),
93        page.waitForFileChooser(),
94        page.$eval('input', input => input.click()),
95      ]);
96      expect(fileChooser1 === fileChooser2).toBe(true);
97    });
98  });
99
100  describe_fails_ffox('FileChooser.accept', function() {
101    it('should accept single file', async({page, server}) => {
102      await page.setContent(`<input type=file oninput='javascript:console.timeStamp()'>`);
103      const [chooser] = await Promise.all([
104        page.waitForFileChooser(),
105        page.click('input'),
106      ]);
107      await Promise.all([
108        chooser.accept([FILE_TO_UPLOAD]),
109        new Promise(x => page.once('metrics', x)),
110      ]);
111      expect(await page.$eval('input', input => input.files.length)).toBe(1);
112      expect(await page.$eval('input', input => input.files[0].name)).toBe('file-to-upload.txt');
113    });
114    it('should be able to read selected file', async({page, server}) => {
115      await page.setContent(`<input type=file>`);
116      page.waitForFileChooser().then(chooser => chooser.accept([FILE_TO_UPLOAD]));
117      expect(await page.$eval('input', async picker => {
118        picker.click();
119        await new Promise(x => picker.oninput = x);
120        const reader = new FileReader();
121        const promise = new Promise(fulfill => reader.onload = fulfill);
122        reader.readAsText(picker.files[0]);
123        return promise.then(() => reader.result);
124      })).toBe('contents of the file');
125    });
126    it('should be able to reset selected files with empty file list', async({page, server}) => {
127      await page.setContent(`<input type=file>`);
128      page.waitForFileChooser().then(chooser => chooser.accept([FILE_TO_UPLOAD]));
129      expect(await page.$eval('input', async picker => {
130        picker.click();
131        await new Promise(x => picker.oninput = x);
132        return picker.files.length;
133      })).toBe(1);
134      page.waitForFileChooser().then(chooser => chooser.accept([]));
135      expect(await page.$eval('input', async picker => {
136        picker.click();
137        await new Promise(x => picker.oninput = x);
138        return picker.files.length;
139      })).toBe(0);
140    });
141    it('should not accept multiple files for single-file input', async({page, server}) => {
142      await page.setContent(`<input type=file>`);
143      const [chooser] = await Promise.all([
144        page.waitForFileChooser(),
145        page.click('input'),
146      ]);
147      let error = null;
148      await chooser.accept([
149        path.relative(process.cwd(), __dirname + '/assets/file-to-upload.txt'),
150        path.relative(process.cwd(), __dirname + '/assets/pptr.png'),
151      ]).catch(e => error = e);
152      expect(error).not.toBe(null);
153    });
154    it('should fail when accepting file chooser twice', async({page, server}) => {
155      await page.setContent(`<input type=file>`);
156      const [fileChooser] = await Promise.all([
157        page.waitForFileChooser(),
158        page.$eval('input', input => input.click()),
159      ]);
160      await fileChooser.accept([]);
161      let error = null;
162      await fileChooser.accept([]).catch(e => error = e);
163      expect(error.message).toBe('Cannot accept FileChooser which is already handled!');
164    });
165  });
166
167  describe_fails_ffox('FileChooser.cancel', function() {
168    it('should cancel dialog', async({page, server}) => {
169      // Consider file chooser canceled if we can summon another one.
170      // There's no reliable way in WebPlatform to see that FileChooser was
171      // canceled.
172      await page.setContent(`<input type=file>`);
173      const [fileChooser1] = await Promise.all([
174        page.waitForFileChooser(),
175        page.$eval('input', input => input.click()),
176      ]);
177      await fileChooser1.cancel();
178      // If this resolves, than we successfully canceled file chooser.
179      await Promise.all([
180        page.waitForFileChooser(),
181        page.$eval('input', input => input.click()),
182      ]);
183    });
184    it('should fail when canceling file chooser twice', async({page, server}) => {
185      await page.setContent(`<input type=file>`);
186      const [fileChooser] = await Promise.all([
187        page.waitForFileChooser(),
188        page.$eval('input', input => input.click()),
189      ]);
190      await fileChooser.cancel();
191      let error = null;
192      await fileChooser.cancel().catch(e => error = e);
193      expect(error.message).toBe('Cannot cancel FileChooser which is already handled!');
194    });
195  });
196
197  describe_fails_ffox('FileChooser.isMultiple', () => {
198    it('should work for single file pick', async({page, server}) => {
199      await page.setContent(`<input type=file>`);
200      const [chooser] = await Promise.all([
201        page.waitForFileChooser(),
202        page.click('input'),
203      ]);
204      expect(chooser.isMultiple()).toBe(false);
205    });
206    it('should work for "multiple"', async({page, server}) => {
207      await page.setContent(`<input multiple type=file>`);
208      const [chooser] = await Promise.all([
209        page.waitForFileChooser(),
210        page.click('input'),
211      ]);
212      expect(chooser.isMultiple()).toBe(true);
213    });
214    it('should work for "webkitdirectory"', async({page, server}) => {
215      await page.setContent(`<input multiple webkitdirectory type=file>`);
216      const [chooser] = await Promise.all([
217        page.waitForFileChooser(),
218        page.click('input'),
219      ]);
220      expect(chooser.isMultiple()).toBe(true);
221    });
222  });
223};
224
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Puppeteer on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)