Skip to content

Commit

Permalink
fix page.injectFile and add test. (puppeteer#52)
Browse files Browse the repository at this point in the history
This line within `injectFile` wasn't doing much of anything: 

```js
let expression = fs.readFile(filePath, 'utf8', (err, data) => callback({err, data}));
```

* That's fixed.
* A path error in examples/features.js is fixed.
* Test added for injectFile.
  • Loading branch information
paulirish authored and aslushnikov committed Jul 6, 2017
1 parent 3d3e8dd commit 6c7ae41
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 6 deletions.
2 changes: 1 addition & 1 deletion examples/features.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ var Browser = require('../lib/Browser');
var browser = new Browser();

browser.newPage().then(async page => {
var modernizrPath = path.join('..', 'third_party', 'phantomjs', 'examples', 'modernizr.js');
var modernizrPath = path.join(__dirname, '../third_party/phantomjs/examples/modernizr.js');
await page.injectFile(modernizrPath);
page.on('consolemessage', console.log);
await page.evaluate(detectFeatures);
Expand Down
12 changes: 7 additions & 5 deletions lib/Page.js
Original file line number Diff line number Diff line change
Expand Up @@ -128,11 +128,13 @@ class Page extends EventEmitter {
* @return {!Promise}
*/
async injectFile(filePath) {
let callback;
let promise = new Promise(fulfill => callback = fulfill);
let expression = fs.readFile(filePath, 'utf8', (err, data) => callback({err, data}));
await promise;
return this._client.send('Runtime.evaluate', { expression, returnByValue: true });
const contents = await new Promise((resolve, reject) => {
fs.readFile(filePath, 'utf8', (err, data) => {
if (err) return reject(err);
resolve(data);
});
});
return this._client.send('Runtime.evaluate', { expression: contents, returnByValue: true });
}

/**
Expand Down
1 change: 1 addition & 0 deletions test/assets/injectedfile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
__injected = 42;
9 changes: 9 additions & 0 deletions test/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,15 @@ describe('Puppeteer', function() {
}));
});

describe('Page.injectFile', function() {
it('should fail when navigating to bad url', SX(async function() {
const helloPath = path.join(__dirname, './assets/injectedfile.js');
await page.injectFile(helloPath);
const result = await page.evaluate(() => __injected);
expect(result).toBe(42);
}));
});

describe('Frame.evaluate', function() {
let FrameUtils = require('./frame-utils');
it('should have different execution contexts', SX(async function() {
Expand Down

0 comments on commit 6c7ae41

Please sign in to comment.