How to use waitForFileChooser method in Puppeteer

Best JavaScript code snippet using puppeteer

input.spec.js

Source:input.spec.js Github

copy

Full Screen

...37 describe_fails_ffox('Page.waitForFileChooser', function() {38 it('should work when file input is attached to DOM', async({page, server}) => {39 await page.setContent(`<input type=file>`);40 const [chooser] = await Promise.all([41 page.waitForFileChooser(),42 page.click('input'),43 ]);44 expect(chooser).toBeTruthy();45 });46 it('should work when file input is not attached to DOM', async({page, server}) => {47 const [chooser] = await Promise.all([48 page.waitForFileChooser(),49 page.evaluate(() => {50 const el = document.createElement('input');51 el.type = 'file';52 el.click();53 }),54 ]);55 expect(chooser).toBeTruthy();56 });57 it('should respect timeout', async({page, server}) => {58 let error = null;59 await page.waitForFileChooser({timeout: 1}).catch(e => error = e);60 expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);61 });62 it('should respect default timeout when there is no custom timeout', async({page, server}) => {63 page.setDefaultTimeout(1);64 let error = null;65 await page.waitForFileChooser().catch(e => error = e);66 expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);67 });68 it('should prioritize exact timeout over default timeout', async({page, server}) => {69 page.setDefaultTimeout(0);70 let error = null;71 await page.waitForFileChooser({timeout: 1}).catch(e => error = e);72 expect(error).toBeInstanceOf(puppeteer.errors.TimeoutError);73 });74 it('should work with no timeout', async({page, server}) => {75 const [chooser] = await Promise.all([76 page.waitForFileChooser({timeout: 0}),77 page.evaluate(() => setTimeout(() => {78 const el = document.createElement('input');79 el.type = 'file';80 el.click();81 }, 50))82 ]);83 expect(chooser).toBeTruthy();84 });85 it('should return the same file chooser when there are many watchdogs simultaneously', async({page, server}) => {86 await page.setContent(`<input type=file>`);87 const [fileChooser1, fileChooser2] = await Promise.all([88 page.waitForFileChooser(),89 page.waitForFileChooser(),90 page.$eval('input', input => input.click()),91 ]);92 expect(fileChooser1 === fileChooser2).toBe(true);93 });94 });95 describe_fails_ffox('FileChooser.accept', function() {96 it('should accept single file', async({page, server}) => {97 await page.setContent(`<input type=file oninput='javascript:console.timeStamp()'>`);98 const [chooser] = await Promise.all([99 page.waitForFileChooser(),100 page.click('input'),101 ]);102 await Promise.all([103 chooser.accept([FILE_TO_UPLOAD]),104 new Promise(x => page.once('metrics', x)),105 ]);106 expect(await page.$eval('input', input => input.files.length)).toBe(1);107 expect(await page.$eval('input', input => input.files[0].name)).toBe('file-to-upload.txt');108 });109 it('should be able to read selected file', async({page, server}) => {110 await page.setContent(`<input type=file>`);111 page.waitForFileChooser().then(chooser => chooser.accept([FILE_TO_UPLOAD]));112 expect(await page.$eval('input', async picker => {113 picker.click();114 await new Promise(x => picker.oninput = x);115 const reader = new FileReader();116 const promise = new Promise(fulfill => reader.onload = fulfill);117 reader.readAsText(picker.files[0]);118 return promise.then(() => reader.result);119 })).toBe('contents of the file');120 });121 it('should be able to reset selected files with empty file list', async({page, server}) => {122 await page.setContent(`<input type=file>`);123 page.waitForFileChooser().then(chooser => chooser.accept([FILE_TO_UPLOAD]));124 expect(await page.$eval('input', async picker => {125 picker.click();126 await new Promise(x => picker.oninput = x);127 return picker.files.length;128 })).toBe(1);129 page.waitForFileChooser().then(chooser => chooser.accept([]));130 expect(await page.$eval('input', async picker => {131 picker.click();132 await new Promise(x => picker.oninput = x);133 return picker.files.length;134 })).toBe(0);135 });136 it('should not accept multiple files for single-file input', async({page, server}) => {137 await page.setContent(`<input type=file>`);138 const [chooser] = await Promise.all([139 page.waitForFileChooser(),140 page.click('input'),141 ]);142 let error = null;143 await chooser.accept([144 path.relative(process.cwd(), __dirname + '/assets/file-to-upload.txt'),145 path.relative(process.cwd(), __dirname + '/assets/pptr.png'),146 ]).catch(e => error = e);147 expect(error).not.toBe(null);148 });149 it('should fail when accepting file chooser twice', async({page, server}) => {150 await page.setContent(`<input type=file>`);151 const [fileChooser] = await Promise.all([152 page.waitForFileChooser(),153 page.$eval('input', input => input.click()),154 ]);155 await fileChooser.accept([]);156 let error = null;157 await fileChooser.accept([]).catch(e => error = e);158 expect(error.message).toBe('Cannot accept FileChooser which is already handled!');159 });160 });161 describe_fails_ffox('FileChooser.cancel', function() {162 it('should cancel dialog', async({page, server}) => {163 // Consider file chooser canceled if we can summon another one.164 // There's no reliable way in WebPlatform to see that FileChooser was165 // canceled.166 await page.setContent(`<input type=file>`);167 const [fileChooser1] = await Promise.all([168 page.waitForFileChooser(),169 page.$eval('input', input => input.click()),170 ]);171 await fileChooser1.cancel();172 // If this resolves, than we successfully canceled file chooser.173 await Promise.all([174 page.waitForFileChooser(),175 page.$eval('input', input => input.click()),176 ]);177 });178 it('should fail when canceling file chooser twice', async({page, server}) => {179 await page.setContent(`<input type=file>`);180 const [fileChooser] = await Promise.all([181 page.waitForFileChooser(),182 page.$eval('input', input => input.click()),183 ]);184 await fileChooser.cancel();185 let error = null;186 await fileChooser.cancel().catch(e => error = e);187 expect(error.message).toBe('Cannot cancel FileChooser which is already handled!');188 });189 });190 describe_fails_ffox('FileChooser.isMultiple', () => {191 it('should work for single file pick', async({page, server}) => {192 await page.setContent(`<input type=file>`);193 const [chooser] = await Promise.all([194 page.waitForFileChooser(),195 page.click('input'),196 ]);197 expect(chooser.isMultiple()).toBe(false);198 });199 it('should work for "multiple"', async({page, server}) => {200 await page.setContent(`<input multiple type=file>`);201 const [chooser] = await Promise.all([202 page.waitForFileChooser(),203 page.click('input'),204 ]);205 expect(chooser.isMultiple()).toBe(true);206 });207 it('should work for "webkitdirectory"', async({page, server}) => {208 await page.setContent(`<input multiple webkitdirectory type=file>`);209 const [chooser] = await Promise.all([210 page.waitForFileChooser(),211 page.click('input'),212 ]);213 expect(chooser.isMultiple()).toBe(true);214 });215 });...

Full Screen

Full Screen

ui-with-photos.js

Source:ui-with-photos.js Github

copy

Full Screen

...113 await page.evaluate(() => {114 window.scrollBy(0, window.innerHeight);115 });116 const [fileChoose1] = await Promise.all([117 page.waitForFileChooser(),118 page.evaluate(() => document.querySelector('.image-1').click()),119 ]);120 await fileChoose1.accept(['/Users/farid/Downloads/temp/IMG_0053.png']);121 await page.waitFor(250);122 const [fileChoose2] = await Promise.all([123 page.waitForFileChooser(),124 page.evaluate(() => document.querySelector('.image-2').click()),125 ]);126 await fileChoose2.accept(['/Users/farid/Downloads/temp/IMG_0098.jpg']);127 await page.waitFor(250);128 const [fileChoose3] = await Promise.all([129 page.waitForFileChooser(),130 page.evaluate(() => document.querySelector('.image-3').click()),131 ]);132 await fileChoose3.accept(['/Users/farid/Downloads/temp/IMG_0093.jpg']);133 await page.waitFor(250);134 const [fileChoose4] = await Promise.all([135 page.waitForFileChooser(),136 page.evaluate(() => document.querySelector('.image-4').click()),137 ]);138 await fileChoose4.accept(['/Users/farid/Downloads/temp/IMG_0092.jpg']);139 await page.waitFor(250);140 const [fileChoose5] = await Promise.all([141 page.waitForFileChooser(),142 page.evaluate(() => document.querySelector('.image-5').click()),143 ]);144 await fileChoose5.accept(['/Users/farid/Downloads/temp/IMG_0097.jpg']);145 await page.waitFor(250);146 const [fileChoose6] = await Promise.all([147 page.waitForFileChooser(),148 page.evaluate(() => document.querySelector('.image-6').click()),149 ]);150 await fileChoose6.accept(['/Users/farid/Downloads/temp/IMG_0096.jpg']);151 await page.waitFor(500);152 await page.waitForSelector('.signup-button');153 await page.click('button[name=createNewAccount]');154 await page.waitFor(5000);155 await page.waitForSelector('#logout');156 await page.evaluate(() => document.querySelector('#logout').click());157 console.log('\n************************************************************');158 }159 } catch (error) {160 console.error(error);161 return browser.close();...

Full Screen

Full Screen

3_verify_account.test.js

Source:3_verify_account.test.js Github

copy

Full Screen

...80 await page.waitFor(1500)8182 //input ktp etc ...83 filePath = path.join(process.cwd()+'/pictures/sample1.png');84 futureFileChooser = page.waitForFileChooser();85 await page.click('label[for="item-upload-ktp"]')86 fileChooser = await futureFileChooser;87 await fileChooser.accept([filePath]);88 await page.waitFor(2000)8990 futureFileChooser = page.waitForFileChooser();91 await page.click('label[for="item-upload-selfie-ktp"]')92 fileChooser = await futureFileChooser;93 await fileChooser.accept([filePath]);94 await page.waitFor(2000)9596 futureFileChooser = page.waitForFileChooser();97 await page.click('label[for="item-upload-ttd"]')98 fileChooser = await futureFileChooser;99 await fileChooser.accept([filePath]);100 await page.waitFor(2000)101102 futureFileChooser = page.waitForFileChooser();103 await page.click('label[for="item-upload-npwp"]')104 fileChooser = await futureFileChooser;105 await fileChooser.accept([filePath]);106 await page.waitFor(2000)107108 await init.src_height().then(async (value)=>{109 await page.setViewport({width: width_mobile,height : value})110 await page.screenshot({111 path: path.join(__dirname,'../../../Renders/Unit/pinaa/'+res_mobile+'/post verify account with checklist npwp- static.png'),112 fullpage: true,113 waitUntil :'domcontentloaded',114 }) 115 }) 116 await page.click('a[class="button yellow full"]') ...

Full Screen

Full Screen

app.js

Source:app.js Github

copy

Full Screen

...76 77 */78 console.log("Posting title.png");79 const [titlePic] = await Promise.all([80 page.waitForFileChooser(),81 page.click(".mTGkH"),82 ]);83 await titlePic.accept(["output/title.png"]);84 await page.waitForXPath(85 '//*[@id="react-root"]/section/footer/div/div/button'86 );87 const addToStoryButton1 = await page.$x(88 '//*[@id="react-root"]/section/footer/div/div/button'89 );90 await addToStoryButton1[0].click();91 await page.waitForXPath("/html/body/div[4]/div/div/div/div[3]/button[2]");92 //Not now Notification Button93 const notiNotNowButton = await page.$x(94 "/html/body/div[4]/div/div/div/div[3]/button[2]"95 );96 await notiNotNowButton[0].click();97 console.log("Posted title.png");98 //comment out the following if you only need to post one story99 /* 100 101 Second Story 102 103 */104 console.log("Posting summary.png");105 const [summaryPic] = await Promise.all([106 page.waitForFileChooser(),107 page.click(".mTGkH"),108 ]);109 await summaryPic.accept(["output/summary.png"]);110 await page.waitForXPath(111 '//*[@id="react-root"]/section/footer/div/div/button'112 );113 const addToStoryButton2 = await page.$x(114 '//*[@id="react-root"]/section/footer/div/div/button'115 );116 await addToStoryButton2[0].click();117 console.log("Posted summary.png");118 /* 119 120 Third Story121 122 */123 await page.waitFor(10 * 1000);124 console.log("Posting link.png");125 const [linkPic] = await Promise.all([126 page.waitForFileChooser(),127 page.click(".mTGkH"),128 ]);129 await linkPic.accept(["output/link.png"]);130 await page.waitForXPath(131 '//*[@id="react-root"]/section/footer/div/div/button'132 );133 const addToStoryButton3 = await page.$x(134 '//*[@id="react-root"]/section/footer/div/div/button'135 );136 await addToStoryButton3[0].click();137 await page.screenshot({138 path: "log.png",139 });140 await page.waitFor(5 * 1000);...

Full Screen

Full Screen

create-farids-user.js

Source:create-farids-user.js Github

copy

Full Screen

...45 await page.evaluate(() => {46 window.scrollBy(0, 100);47 });48 const [fileChoose1] = await Promise.all([49 page.waitForFileChooser(),50 page.evaluate(() => document.querySelector(".image-1").click()),51 ]);52 await fileChoose1.accept(["/Users/farid/Downloads/temp/IMG_0041.jpg"]);53 await page.waitFor(250);54 const [fileChoose2] = await Promise.all([55 page.waitForFileChooser(),56 page.evaluate(() => document.querySelector(".image-2").click()),57 ]);58 await fileChoose2.accept(["/Users/farid/Downloads/temp/IMG_0047.jpg"]);59 await page.waitFor(250);60 const [fileChoose3] = await Promise.all([61 page.waitForFileChooser(),62 page.evaluate(() => document.querySelector(".image-3").click()),63 ]);64 await fileChoose3.accept(["/Users/farid/Downloads/temp/IMG_0048.jpg"]);65 await page.waitFor(250);66 const [fileChoose4] = await Promise.all([67 page.waitForFileChooser(),68 page.evaluate(() => document.querySelector(".image-4").click()),69 ]);70 await fileChoose4.accept(["/Users/farid/Downloads/temp/IMG_0051.jpg"]);71 await page.waitFor(250);72 const [fileChoose5] = await Promise.all([73 page.waitForFileChooser(),74 page.evaluate(() => document.querySelector(".image-5").click()),75 ]);76 await fileChoose5.accept(["/Users/farid/Downloads/temp/IMG_0053.jpg"]);77 await page.waitFor(250);78 const [fileChoose6] = await Promise.all([79 page.waitForFileChooser(),80 page.evaluate(() => document.querySelector(".image-6").click()),81 ]);82 await fileChoose6.accept(["/Users/farid/Downloads/temp/IMG_0063.jpg"]);83 await page.waitFor(500);84 await page.waitForSelector(".signup-button");85 await page.click("button[name=createNewAccount]");86 await page.waitFor(500);87 await page.waitForSelector("#logout");88 await page.evaluate(() => document.querySelector("#logout").click());89 };90 await createFaridsUser();91 console.log("done");92 await browser.close();93})();

Full Screen

Full Screen

fileupload-advanced.puppeteer-spec.js

Source:fileupload-advanced.puppeteer-spec.js Github

copy

Full Screen

...12 it('should upload a file and show description', async () => {13 // click on Select File14 // file upload should pop up15 const [fileChooser] = await Promise.all([16 page.waitForFileChooser(),17 page.click('.hyperlink')18 ]);19 await fileChooser.accept([filePath]);20 // Description bar21 await page.waitForSelector('.file-row', { visible: true })22 .then(async (element) => {23 const description = await element.$eval('.description', e => e.textContent);24 const progress = await element.$eval('.l-pull-right .size', e => e.textContent.split(' '));25 expect(description).toEqual(fileName);26 expect(Number.parseFloat(progress[0])).toBeTruthy();27 expect(progress[1]).toEqual('KB');28 expect(progress[3]).toContain('%');29 });30 });31 it('should upload a file and show progress bar', async () => {32 const [fileChooser] = await Promise.all([33 page.waitForFileChooser(),34 page.click('.hyperlink')35 ]);36 await fileChooser.accept([filePath]);37 // Progress bar38 await page.waitForSelector('.progress-row', { visible: true })39 .then(element => element.$('.progress'))40 .then(progress => expect(progress).toBeDefined());41 });42 });43 describe('File example failed status', () => {44 const testFile = 'testfile.pdf';45 const url = `${baseUrl}/example-failed.html`;46 const filePath = path.resolve(__dirname, testFile);47 beforeEach(async () => {48 await page.goto(url, { waitUntil: ['domcontentloaded', 'networkidle2'] });49 });50 it('should upload a file and show progress bar', async () => {51 const [fileChooser] = await Promise.all([52 page.waitForFileChooser(),53 page.click('.hyperlink')54 ]);55 await fileChooser.accept([filePath]);56 // Progress bar57 await page.waitForSelector('.progress-row', { visible: true })58 .then(element => element.$('.progress'))59 .then(progress => expect(progress).toBeDefined());60 });61 it('should set failed status ', async () => {62 // click on Select File63 // file upload should pop up64 const [fileChooser] = await Promise.all([65 page.waitForFileChooser(),66 page.click('.hyperlink')67 ]);68 await fileChooser.accept([filePath]);69 await page.click('#set-failed');70 // File failed error message71 await page.waitForSelector('.msg', { visible: true })72 .then(async (element) => {73 const errorMessage = await element.$eval('.msg > p', e => e.textContent);74 expect(errorMessage).toContain('File failed error message');75 });76 // Toast77 await page.waitForSelector('.toast-message', { visible: true })78 .then(async (element) => {79 const errorMessage = await element.evaluate(e => e.textContent);...

Full Screen

Full Screen

server.js

Source:server.js Github

copy

Full Screen

...47 });48 await page.waitForSelector('#input_text_area_review');49 await page.type('#input_text_area_review', `${req.body.descripcion}`);50 const [fileChooser1] = await Promise.all([51 page.waitForFileChooser(),52 page.click('.file-input'),53 ]);54 55 //Path a cambiar dependiendo la imagen a subir56 await fileChooser1.accept(['/Users/Quijano/Downloads/prueba1.png']);57 const [fileChooser2] = await Promise.all([58 page.waitForFileChooser(),59 page.click('.file-input'),60 ]);61 62 //Path a cambiar dependiendo la imagen a subir63 await fileChooser2.accept(['/Users/Quijano/Downloads/prueba2.png']);64 const [fileChooser3] = await Promise.all([65 page.waitForFileChooser(),66 page.click('.file-input'),67 ]);68 69 //Path a cambiar dependiendo la imagen a subir70 await fileChooser3.accept(['/Users/Quijano/Downloads/prueba3.png']);71 await page.waitForSelector("li[data-key='2']");72 await page.click("button[class='next-button']");73 await page.waitForSelector('#cancelButton');74 await page.click("#cancelButton");75 await page.screenshot({path: 'frontend/src/images/example.png'});76 await browser.close();77 res.send(`Publicado`);78})79app.get('/', (req,res) => {...

Full Screen

Full Screen

download_upload.test.js

Source:download_upload.test.js Github

copy

Full Screen

...27 });28 test("Upload", async (done) => {29 let page = await p.newPage(`http://${TEST_APP_HOST}:3000/posts/new`);30 let newPostPage = new NewPostPage(page);31 let fileChooser = newPostPage.waitForFileChooser();32 let inputBtn = await newPostPage.imageChooseFileInput();33 // waitForFileChooser must be called before the file chooser is launched.34 await inputBtn.click();35 let chooser = await fileChooser;36 await chooser.accept([`${ROOT_DIR}/images/sunflower1.jpg`]);37 expect(await chooser.isMultiple()).toBeFalsy();38 const postPage = await newPostPage.clickSubmitBtn();39 let message = await (await postPage.flashNotice()).innerText();40 expect(message).toBe("Post was successfully created.");41 let src = await (await postPage.imageElement()).getProperty("src");42 expect(src).toMatch(/sunflower1\.jpg$/);43 done();44 });45});

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch({headless: false});4 const page = await browser.newPage();5 await page.setViewport({6 });7 await page.waitForSelector('#iframeResult');8 const frame = await page.frames().find(f => f.name() === 'iframeResult');9 await frame.waitForSelector('#myFile');10 await frame.click('#myFile');11 const [fileChooser] = await Promise.all([12 page.waitForFileChooser(),13 ]);14 await fileChooser.accept(['./test.txt']);15 await page.waitFor(5000);16 await browser.close();17})();18const puppeteer = require('puppeteer');19(async () => {20 const browser = await puppeteer.launch({headless: false});21 const page = await browser.newPage();22 await page.setViewport({23 });24 await page.waitForSelector('#iframeResult');25 const frame = await page.frames().find(f => f.name() === 'iframeResult');26 await frame.waitForSelector('#myFile');27 await frame.click('#myFile');28 const [fileChooser] = await Promise.all([29 page.waitForFileChooser(),30 ]);31 await fileChooser.accept(['./test.txt']);32 await page.waitFor(500

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page.click('input[type=file]');6 const fileChooser = await page.waitForFileChooser();7 await fileChooser.accept(['path/to/file']);8 await page.screenshot({path: 'example.png'});9 await browser.close();10})();11const puppeteer = require('puppeteer');12(async () => {13 const browser = await puppeteer.launch();14 const page = await browser.newPage();15 await page.click('input[type=file]');16 const fileChooser = await page.waitForFileChooser();17 await fileChooser.accept(['path/to/file']);18 await page.screenshot({path: 'example.png'});19 await browser.close();20})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 const [fileChooser] = await Promise.all([6 page.waitForFileChooser(),7 ]);8 await fileChooser.accept(['/tmp/myfile.pdf']);9 await page.waitFor(1000);10 await browser.close();11})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require("puppeteer");2(async () => {3 const browser = await puppeteer.launch();4 const page = await browser.newPage();5 await page.click("input[type=file]");6 const [fileChooser] = await Promise.all([7 page.waitForFileChooser(),8 ]);9 await fileChooser.accept(["/tmp/myfile.pdf"]);10 await browser.close();11})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const puppeteer = require('puppeteer');2const fs = require('fs');3const fileToUpload = './sample.pdf';4(async () => {5 const browser = await puppeteer.launch();6 const page = await browser.newPage();7 const frame = page.frames()[1];8 const fileInput = await frame.$('#myFile');9 fileInput.uploadFile(fileToUpload);10 await frame.$eval('#submitbtn', el => el.click());11 const [fileChooser] = await Promise.all([12 page.waitForFileChooser(),13 ]);14 await fileChooser.accept([fileToUpload]);15 await browser.close();16})();

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Puppeteer automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful