Skip to content

Feat/download file puppeteer #1343

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

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions docs/helpers/Puppeteer.md
Original file line number Diff line number Diff line change
Expand Up @@ -453,6 +453,19 @@ I.doubleClick('.btn.edit');
- `locator` clickable link or button located by text, or any element located by CSS|XPath|strict locator.
- `context` (optional) element to search in CSS|XPath|Strict locator.

### downloadFile

Performs a download file on an element matched by link|button|CSS or XPath.
File is downloaded by default to output folder

```js
I.downloadFile('td[class="text-right file-link"] a');
```

#### Parameters

- `locator` clickable link or button located by CSS|XPath locator.

### dragAndDrop

Drag an item to a destination element.
Expand Down
9 changes: 9 additions & 0 deletions docs/webapi/downloadFile.mustache
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
Performs a download file on an element matched by link|button|CSS or XPath.
File is downloaded by default to output folder


```js
I.downloadFile('td[class="text-right file-link"] a');
```

@param locator clickable link or button located by CSS|XPath locator.
45 changes: 44 additions & 1 deletion lib/helper/Puppeteer.js
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,8 @@ const path = require('path');
const ElementNotFound = require('./errors/ElementNotFound');
const Popup = require('./extras/Popup');
const Console = require('./extras/Console');

const request = require('request-promise');
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

request-promise is outdated. Let's switch to axios

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I created another PR to follow up this -> #1542

const fs = require('fs');

let puppeteer;
const popupStore = new Popup();
Expand Down Expand Up @@ -814,6 +815,48 @@ class Puppeteer extends Helper {
return proceedClick.call(this, locator, context, { waitForNavigation: true });
}

/**
* {{> ../webapi/downloadFile }}
*/
async downloadFile(locator) {
let fileName;
await this.page.setRequestInterception(true);
this.click(locator);

const xRequest = await new Promise((resolve) => {
this.page.on('request', (request) => {
fileName = request.url().split('/')[request.url().split('/').length - 1];
request.abort();
resolve(request);
});
});

const options = {
encoding: null,
method: xRequest._method,
uri: xRequest._url,
body: xRequest._postData,
headers: xRequest._headers,
};

const cookies = await this.page.cookies();
options.headers.Cookie = cookies.map(ck => `${ck.name}=${ck.value}`).join(';');

const response = await request(options);

const outputFile = path.join(`${global.output_dir}/${fileName}`);

try {
const wstream = fs.createWriteStream(outputFile);
wstream.write(response);
wstream.end();
this.debug(`File is downloaded in ${outputFile}`);
return outputFile;
} catch (error) {
throw new Error(`There is something wrong with downloaded file. ${error}`);
}
}

/**
* {{> ../webapi/doubleClick }}
*/
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@
"mocha": "^4.1.0",
"parse-function": "^5.2.10",
"promise-retry": "^1.1.1",
"request-promise": "^4.2.2",
"requireg": "^0.1.8",
"sprintf-js": "^1.1.1"
},
Expand Down
29 changes: 29 additions & 0 deletions test/helper/Puppeteer_test.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@ describe('Puppeteer', function () {

before(() => {
global.codecept_dir = path.join(__dirname, '/../data');

// create directory /download;
fs.mkdir(path.join(`${__dirname}/download`), () => {

});

global.output_dir = path.join(`${__dirname}/download`);
I = new Puppeteer({
url: siteUrl,
windowSize: '500x700',
Expand Down Expand Up @@ -50,6 +57,19 @@ describe('Puppeteer', function () {
return I._after();
});

after(() => {
// Remove the test dir
fs.readdir(global.output_dir, (err, files) => {
if (err) throw err;

for (const file of files) {
fs.unlink(path.join(global.output_dir, file), (err) => {
if (err) throw err;
});
}
});
});

describe('open page : #amOnPage', () => {
it('should open main page of configured site', async () => {
await I.amOnPage('/');
Expand Down Expand Up @@ -557,4 +577,13 @@ describe('Puppeteer', function () {
assert.notEqual(before, after);
});
});

describe('#downloadFile', () => {
it('should dowload file', async () => {
await I.amOnPage('http://file-examples.com/index.php/sample-video-files/sample-mp4-files/');
const outputFile = await I.downloadFile('td[class="text-right file-link"] a');

assert.equal(fs.existsSync(path.join(outputFile)), true);
});
});
});