chore(firefox): kill original puppeteer-firefox tests (#4047)

When we started working on Puppeteer-Firefox, we forked original
Puppeteer testsuite.

This patch concludes the effort to merge testsuites back together.

Fixes #3889
This commit is contained in:
Andrey Lushnikov 2019-02-21 13:10:15 -08:00 committed by GitHub
parent fbf91cca98
commit ed984ac479
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
102 changed files with 10 additions and 4275 deletions

View File

@ -1,7 +0,0 @@
set -e
total=`git grep ' \* \[' README.md| wc -l`
complete=`git grep ' \* \[x' README.md | wc -l`
ratio=`echo "$complete / $total * 100" | bc -l`
printf "%.2f%%\n" $ratio

View File

@ -13,9 +13,6 @@
},
"scripts": {
"install": "node install.js",
"unit": "node test/test.js",
"funit": "cross-env DUMPIO=1 PRODUCT=firefox node test/test.js",
"cunit": "cross-env PRODUCT=chromium node test/test.js",
"tsc": "tsc -p ."
},
"author": "The Chromium Authors",
@ -28,27 +25,5 @@
"progress": "^2.0.1",
"proxy-from-env": "^1.0.0",
"rimraf": "^2.6.1"
},
"devDependencies": {
"puppeteer": "^1.11.0",
"@pptr/testrunner": "^0.5.0",
"@pptr/testserver": "^0.5.0",
"@types/debug": "0.0.31",
"@types/extract-zip": "^1.6.2",
"@types/mime": "^2.0.0",
"@types/node": "^8.10.34",
"@types/rimraf": "^2.0.2",
"@types/ws": "^6.0.1",
"commonmark": "^0.28.1",
"cross-env": "^5.0.5",
"eslint": "^5.9.0",
"esprima": "^4.0.0",
"jpeg-js": "^0.3.4",
"minimist": "^1.2.0",
"ncp": "^2.0.0",
"pixelmatch": "^4.0.2",
"pngjs": "^3.3.3",
"text-diff": "^1.0.1",
"typescript": "3.1.6"
}
}

View File

@ -1,11 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>console.log test</title>
</head>
<body>
<script>
console.log('yellow')
</script>
</body>
</html>

View File

@ -1 +0,0 @@
<meta http-equiv="Content-Security-Policy" content="default-src 'self'">

View File

@ -1,12 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>Detect Touch Test</title>
<script src='modernizr.js'></script>
</head>
<body style="font-size:30vmin">
<script>
document.body.textContent = Modernizr.touchevents ? 'YES' : 'NO';
</script>
</body>
</html>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 434 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 346 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 413 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 434 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 403 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 422 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 445 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 387 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 447 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 437 B

View File

@ -1,15 +0,0 @@
<script>
a();
function a() {
b();
}
function b() {
c();
}
function c() {
throw new Error('Fancy error!');
}
</script>

View File

@ -1,2 +0,0 @@
import num from './es6module.js';
window.__es6injected = num;

View File

@ -1 +0,0 @@
export default 42;

View File

@ -1,2 +0,0 @@
import num from './es6/es6module.js';
window.__es6injected = num;

View File

@ -1,8 +0,0 @@
<link rel='stylesheet' href='./style.css'>
<script src='./script.js' type='text/javascript'></script>
<style>
div {
line-height: 18px;
}
</style>
<div>Hi, I'm frame</div>

View File

@ -1,8 +0,0 @@
<frameset>
<frameset>
<frame src='./frame.html'></frame>
<frame src='about:blank'></frame>
</frameset>
<frame src='/empty.html'></frame>
<frame></frame>
</frameset>

View File

@ -1,25 +0,0 @@
<style>
body {
display: flex;
}
body iframe {
flex-grow: 1;
flex-shrink: 1;
}
::-webkit-scrollbar{
display: none;
}
</style>
<script>
async function attachFrame(frameId, url) {
var frame = document.createElement('iframe');
frame.src = url;
frame.id = frameId;
document.body.appendChild(frame);
await new Promise(x => frame.onload = x);
return 'kazakh';
}
</script>
<iframe src='./two-frames.html' name='2frames'></iframe>
<iframe src='./frame.html' name='aframe'></iframe>

View File

@ -1 +0,0 @@
<iframe src='./frame.html'></iframe>

View File

@ -1 +0,0 @@
console.log('Cheers!');

View File

@ -1,3 +0,0 @@
div {
color: blue;
}

View File

@ -1,13 +0,0 @@
<style>
body {
display: flex;
flex-direction: column;
}
body iframe {
flex-grow: 1;
flex-shrink: 1;
}
</style>
<iframe src='./frame.html' name='uno'></iframe>
<iframe src='./frame.html' name='dos'></iframe>

View File

@ -1,3 +0,0 @@
<script>
var globalVar = 123;
</script>

View File

@ -1,52 +0,0 @@
<script>
document.addEventListener('DOMContentLoaded', function() {
function generatePalette(amount) {
var result = [];
var hueStep = 360 / amount;
for (var i = 0; i < amount; ++i)
result.push('hsl(' + (hueStep * i) + ', 100%, 90%)');
return result;
}
var palette = generatePalette(100);
for (var i = 0; i < 200; ++i) {
var box = document.createElement('div');
box.classList.add('box');
box.style.setProperty('background-color', palette[i % palette.length]);
var x = i;
do {
var digit = x % 10;
x = (x / 10)|0;
var img = document.createElement('img');
img.src = `./digits/${digit}.png`;
box.insertBefore(img, box.firstChild);
} while (x);
document.body.appendChild(box);
}
});
</script>
<style>
body {
margin: 0;
padding: 0;
}
.box {
font-family: arial;
display: inline-flex;
align-items: center;
justify-content: center;
margin: 0;
padding: 0;
width: 50px;
height: 50px;
box-sizing: border-box;
border: 1px solid darkgray;
}
::-webkit-scrollbar {
display: none;
}
</style>

View File

@ -1,2 +0,0 @@
window.__injected = 42;
window.__injectedError = new Error('hi');

View File

@ -1,3 +0,0 @@
body {
background-color: red;
}

View File

@ -1,16 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>Button test</title>
</head>
<body>
<script src="mouse-helper.js"></script>
<button onclick="clicked();">Click target</button>
<script>
window.result = 'Was not clicked';
function clicked() {
result = 'Clicked';
}
</script>
</body>
</html>

View File

@ -1,42 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>Selection Test</title>
</head>
<body>
<label for="agree">Remember Me</label>
<input id="agree" type="checkbox">
<script>
window.result = {
check: null,
events: [],
};
let checkbox = document.querySelector('input');
const events = [
'change',
'click',
'dblclick',
'input',
'mousedown',
'mouseenter',
'mouseleave',
'mousemove',
'mouseout',
'mouseover',
'mouseup',
];
for (let event of events) {
checkbox.addEventListener(event, () => {
if (['change', 'click', 'dblclick', 'input'].includes(event) === true) {
result.check = checkbox.checked;
}
result.events.push(event);
}, false);
}
</script>
</body>
</html>

View File

@ -1,44 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>Keyboard test</title>
</head>
<body>
<textarea></textarea>
<script>
window.result = "";
let textarea = document.querySelector('textarea');
textarea.focus();
textarea.addEventListener('keydown', event => {
log('Keydown:', event.key, event.code, event.which, modifiers(event));
});
textarea.addEventListener('keypress', event => {
log('Keypress:', event.key, event.code, event.which, event.charCode, modifiers(event));
});
textarea.addEventListener('keyup', event => {
log('Keyup:', event.key, event.code, event.which, modifiers(event));
});
function modifiers(event) {
let m = [];
if (event.altKey)
m.push('Alt')
if (event.ctrlKey)
m.push('Control');
if (event.metaKey)
m.push('Meta')
if (event.shiftKey)
m.push('Shift')
return '[' + m.join(' ') + ']';
}
function log(...args) {
console.log.apply(console, args);
result += args.join(' ') + '\n';
}
function getResult() {
let temp = result.trim();
result = "";
return temp;
}
</script>
</body>
</html>

View File

@ -1,23 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>Scrollable test</title>
</head>
<body>
<script src='mouse-helper.js'></script>
<script>
for (let i = 0; i < 100; i++) {
let button = document.createElement('button');
button.textContent = i + ': not clicked';
button.id = 'button-' + i;
button.onclick = () => button.textContent = 'clicked';
button.oncontextmenu = event => {
event.preventDefault();
button.textContent = 'context menu';
}
document.body.appendChild(button);
document.body.appendChild(document.createElement('br'));
}
</script>
</body>
</html>

View File

@ -1,69 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>Selection Test</title>
</head>
<body>
<select>
<option value="black">Black</option>
<option value="blue">Blue</option>
<option value="brown">Brown</option>
<option value="cyan">Cyan</option>
<option value="gray">Gray</option>
<option value="green">Green</option>
<option value="indigo">Indigo</option>
<option value="magenta">Magenta</option>
<option value="orange">Orange</option>
<option value="pink">Pink</option>
<option value="purple">Purple</option>
<option value="red">Red</option>
<option value="violet">Violet</option>
<option value="white">White</option>
<option value="yellow">Yellow</option>
</select>
<script>
window.result = {
onInput: null,
onChange: null,
onBubblingChange: null,
onBubblingInput: null,
};
let select = document.querySelector('select');
function makeEmpty() {
for (let i = select.options.length - 1; i >= 0; --i) {
select.remove(i);
}
}
function makeMultiple() {
select.setAttribute('multiple', true);
}
select.addEventListener('input', () => {
result.onInput = Array.from(select.querySelectorAll('option:checked')).map((option) => {
return option.value;
});
}, false);
select.addEventListener('change', () => {
result.onChange = Array.from(select.querySelectorAll('option:checked')).map((option) => {
return option.value;
});
}, false);
document.body.addEventListener('input', () => {
result.onBubblingInput = Array.from(select.querySelectorAll('option:checked')).map((option) => {
return option.value;
});
}, false);
document.body.addEventListener('change', () => {
result.onBubblingChange = Array.from(select.querySelectorAll('option:checked')).map((option) => {
return option.value;
});
}, false);
</script>
</body>
</html>

View File

@ -1,15 +0,0 @@
<!DOCTYPE html>
<html>
<head>
<title>Textarea test</title>
</head>
<body>
<textarea></textarea>
<script src='mouse-helper.js'></script>
<script>
window.result = '';
let textarea = document.querySelector('textarea');
textarea.addEventListener('input', () => result = textarea.value, false);
</script>
</body>
</html>

View File

@ -1 +0,0 @@
<meta name = "viewport" content = "initial-scale = 1, user-scalable = no">

View File

@ -1,3 +0,0 @@
/*! modernizr 3.5.0 (Custom Build) | MIT *
* https://modernizr.com/download/?-touchevents-setclasses !*/
!function(e,n,t){function o(e,n){return typeof e===n}function s(){var e,n,t,s,a,i,r;for(var l in c)if(c.hasOwnProperty(l)){if(e=[],n=c[l],n.name&&(e.push(n.name.toLowerCase()),n.options&&n.options.aliases&&n.options.aliases.length))for(t=0;t<n.options.aliases.length;t++)e.push(n.options.aliases[t].toLowerCase());for(s=o(n.fn,"function")?n.fn():n.fn,a=0;a<e.length;a++)i=e[a],r=i.split("."),1===r.length?Modernizr[r[0]]=s:(!Modernizr[r[0]]||Modernizr[r[0]]instanceof Boolean||(Modernizr[r[0]]=new Boolean(Modernizr[r[0]])),Modernizr[r[0]][r[1]]=s),f.push((s?"":"no-")+r.join("-"))}}function a(e){var n=u.className,t=Modernizr._config.classPrefix||"";if(p&&(n=n.baseVal),Modernizr._config.enableJSClass){var o=new RegExp("(^|\\s)"+t+"no-js(\\s|$)");n=n.replace(o,"$1"+t+"js$2")}Modernizr._config.enableClasses&&(n+=" "+t+e.join(" "+t),p?u.className.baseVal=n:u.className=n)}function i(){return"function"!=typeof n.createElement?n.createElement(arguments[0]):p?n.createElementNS.call(n,"http://www.w3.org/2000/svg",arguments[0]):n.createElement.apply(n,arguments)}function r(){var e=n.body;return e||(e=i(p?"svg":"body"),e.fake=!0),e}function l(e,t,o,s){var a,l,f,c,d="modernizr",p=i("div"),h=r();if(parseInt(o,10))for(;o--;)f=i("div"),f.id=s?s[o]:d+(o+1),p.appendChild(f);return a=i("style"),a.type="text/css",a.id="s"+d,(h.fake?h:p).appendChild(a),h.appendChild(p),a.styleSheet?a.styleSheet.cssText=e:a.appendChild(n.createTextNode(e)),p.id=d,h.fake&&(h.style.background="",h.style.overflow="hidden",c=u.style.overflow,u.style.overflow="hidden",u.appendChild(h)),l=t(p,e),h.fake?(h.parentNode.removeChild(h),u.style.overflow=c,u.offsetHeight):p.parentNode.removeChild(p),!!l}var f=[],c=[],d={_version:"3.5.0",_config:{classPrefix:"",enableClasses:!0,enableJSClass:!0,usePrefixes:!0},_q:[],on:function(e,n){var t=this;setTimeout(function(){n(t[e])},0)},addTest:function(e,n,t){c.push({name:e,fn:n,options:t})},addAsyncTest:function(e){c.push({name:null,fn:e})}},Modernizr=function(){};Modernizr.prototype=d,Modernizr=new Modernizr;var u=n.documentElement,p="svg"===u.nodeName.toLowerCase(),h=d._config.usePrefixes?" -webkit- -moz- -o- -ms- ".split(" "):["",""];d._prefixes=h;var m=d.testStyles=l;Modernizr.addTest("touchevents",function(){var t;if("ontouchstart"in e||e.DocumentTouch&&n instanceof DocumentTouch)t=!0;else{var o=["@media (",h.join("touch-enabled),("),"heartz",")","{#modernizr{top:9px;position:absolute}}"].join("");m(o,function(e){t=9===e.offsetTop})}return t}),s(),a(f),delete d.addTest,delete d.addAsyncTest;for(var v=0;v<Modernizr._q.length;v++)Modernizr._q[v]();e.Modernizr=Modernizr}(window,document);

View File

@ -1,36 +0,0 @@
<style>
button {
position: absolute;
width: 100px;
height: 20px;
}
#btn0 { right: 0px; top: 0; }
#btn1 { right: -10px; top: 25px; }
#btn2 { right: -20px; top: 50px; }
#btn3 { right: -30px; top: 75px; }
#btn4 { right: -40px; top: 100px; }
#btn5 { right: -50px; top: 125px; }
#btn6 { right: -60px; top: 150px; }
#btn7 { right: -70px; top: 175px; }
#btn8 { right: -80px; top: 200px; }
#btn9 { right: -90px; top: 225px; }
#btn10 { right: -100px; top: 250px; }
</style>
<button id=btn0>0</button>
<button id=btn1>1</button>
<button id=btn2>2</button>
<button id=btn3>3</button>
<button id=btn4>4</button>
<button id=btn5>5</button>
<button id=btn6>6</button>
<button id=btn7>7</button>
<button id=btn8>8</button>
<button id=btn9>9</button>
<button id=btn10>10</button>
<script>
window.addEventListener('DOMContentLoaded', () => {
for (const button of Array.from(document.querySelectorAll('button')))
button.addEventListener('click', () => console.log('button #' + button.textContent + ' clicked'), false);
}, false);
</script>

View File

@ -1,3 +0,0 @@
body {
background-color: pink;
}

View File

@ -1,2 +0,0 @@
<link rel='stylesheet' href='./one-style.css'>
<div>hello, world!</div>

View File

@ -1,3 +0,0 @@
<script>
window.result = window.injected;
</script>

View File

@ -1 +0,0 @@
<title>Woof-Woof</title>

View File

@ -1,32 +0,0 @@
<style>
:root {
font-family: monospace;
}
body {
display: flex;
align-items: center;
justify-content: center;
}
div {
width: 10ch;
word-wrap: break-word;
border: 1px solid blue;
transform: rotate(33deg);
line-height: 8ch;
padding: 2ch;
}
a {
margin-left: 7ch;
}
</style>
<div>
<a href='#clicked'>123321</a>
</div>
<script>
document.querySelector('a').addEventListener('click', () => {
window.__clicked = true;
});
</script>

View File

@ -1,30 +0,0 @@
/**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
module.exports.addTests = function({testRunner, expect, product}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
describe('Browser.process', function() {
it('should return child_process instance', async function({browser}) {
const process = await browser.process();
expect(process.pid).toBeGreaterThan(0);
});
});
};

View File

@ -1,160 +0,0 @@
/**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const utils = require('./utils');
const {TimeoutError} = require('../Errors');
module.exports.addTests = function({testRunner, expect, puppeteer, product}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
const FFOX = product === 'firefox';
const CHROME = product === 'chromium';
describe('BrowserContext', function() {
it('should have default context', async function({browser, server}) {
expect(browser.browserContexts().length).toBe(1);
const defaultContext = browser.browserContexts()[0];
expect(defaultContext.isIncognito()).toBe(false);
let error = null;
await defaultContext.close().catch(e => error = e);
expect(browser.defaultBrowserContext()).toBe(defaultContext);
expect(error.message).toContain('cannot be closed');
});
it('should create new incognito context', async function({browser, server}) {
expect(browser.browserContexts().length).toBe(1);
const context = await browser.createIncognitoBrowserContext();
expect(context.isIncognito()).toBe(true);
expect(browser.browserContexts().length).toBe(2);
expect(browser.browserContexts().indexOf(context) !== -1).toBe(true);
await context.close();
expect(browser.browserContexts().length).toBe(1);
});
it('should close all belonging targets once closing context', async function({browser, server}) {
expect((await browser.pages()).length).toBe(1);
const context = await browser.createIncognitoBrowserContext();
await context.newPage();
expect((await browser.pages()).length).toBe(2);
expect((await context.pages()).length).toBe(1);
await context.close();
expect((await browser.pages()).length).toBe(1);
});
it('window.open should use parent tab context', async function({browser, server}) {
const context = await browser.createIncognitoBrowserContext();
const page = await context.newPage();
await page.goto(server.EMPTY_PAGE);
const [popupTarget] = await Promise.all([
utils.waitEvent(browser, 'targetcreated'),
page.evaluate(url => window.open(url), server.EMPTY_PAGE)
]);
expect(popupTarget.browserContext()).toBe(context);
await context.close();
});
it('should fire target events', async function({browser, server}) {
const context = await browser.createIncognitoBrowserContext();
const events = [];
context.on('targetcreated', target => events.push('CREATED: ' + target.url()));
context.on('targetchanged', target => events.push('CHANGED: ' + target.url()));
context.on('targetdestroyed', target => events.push('DESTROYED: ' + target.url()));
const page = await context.newPage();
await page.goto(server.EMPTY_PAGE);
await page.close();
expect(events).toEqual([
'CREATED: about:blank',
`CHANGED: ${server.EMPTY_PAGE}`,
`DESTROYED: ${server.EMPTY_PAGE}`
]);
await context.close();
});
it('should wait for a target', async function({browser, server}) {
const context = await browser.createIncognitoBrowserContext();
let resolved = false;
const targetPromise = context.waitForTarget(target => target.url() === server.EMPTY_PAGE);
targetPromise.then(() => resolved = true);
const page = await context.newPage();
expect(resolved).toBe(false);
await page.goto(server.EMPTY_PAGE);
const target = await targetPromise;
expect(await target.page()).toBe(page);
await context.close();
});
it('should timeout waiting for a non-existent target', async function({browser, server}) {
const context = await browser.createIncognitoBrowserContext();
const error = await context.waitForTarget(target => target.url() === server.EMPTY_PAGE, {timeout: 1}).catch(e => e);
expect(error).toBeInstanceOf(TimeoutError);
await context.close();
});
it('should isolate localStorage and cookies', async function({browser, server}) {
// Create two incognito contexts.
const context1 = await browser.createIncognitoBrowserContext();
const context2 = await browser.createIncognitoBrowserContext();
expect(context1.targets().length).toBe(0);
expect(context2.targets().length).toBe(0);
// Create a page in first incognito context.
const page1 = await context1.newPage();
await page1.goto(server.EMPTY_PAGE);
await page1.evaluate(() => {
localStorage.setItem('name', 'page1');
document.cookie = 'name=page1';
});
expect(context1.targets().length).toBe(1);
expect(context2.targets().length).toBe(0);
// Create a page in second incognito context.
const page2 = await context2.newPage();
await page2.goto(server.EMPTY_PAGE);
await page2.evaluate(() => {
localStorage.setItem('name', 'page2');
document.cookie = 'name=page2';
});
expect(context1.targets().length).toBe(1);
expect(context1.targets()[0]).toBe(page1.target());
expect(context2.targets().length).toBe(1);
expect(context2.targets()[0]).toBe(page2.target());
// Make sure pages don't share localstorage or cookies.
expect(await page1.evaluate(() => localStorage.getItem('name'))).toBe('page1');
expect(await page1.evaluate(() => document.cookie)).toBe('name=page1');
expect(await page2.evaluate(() => localStorage.getItem('name'))).toBe('page2');
expect(await page2.evaluate(() => document.cookie)).toBe('name=page2');
// Cleanup contexts.
await Promise.all([
context1.close(),
context2.close()
]);
expect(browser.browserContexts().length).toBe(1);
});
(FFOX ? xit : it)('should work across sessions', async function({browser, server}) {
expect(browser.browserContexts().length).toBe(1);
const context = await browser.createIncognitoBrowserContext();
expect(browser.browserContexts().length).toBe(2);
const remoteBrowser = await puppeteer.connect({
browserWSEndpoint: browser.wsEndpoint()
});
const contexts = remoteBrowser.browserContexts();
expect(contexts.length).toBe(2);
await remoteBrowser.disconnect();
await context.close();
});
});
};

View File

@ -1,24 +0,0 @@
module.exports.addTests = function({testRunner, expect, product}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
describe('Chromium-specific tests', function() {
describe('Browser.version', function() {
xit('should return whether we are in headless', async({browser}) => {
const version = await browser.version();
expect(version.length).toBeGreaterThan(0);
expect(version.startsWith('Headless')).toBe(headless);
});
});
describe('Browser.userAgent', function() {
it('should include WebKit', async({browser}) => {
const userAgent = await browser.userAgent();
expect(userAgent.length).toBeGreaterThan(0);
expect(userAgent).toContain('WebKit');
});
});
});
};

View File

@ -1,211 +0,0 @@
/**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const utils = require('./utils');
const os = require('os');
const DeviceDescriptors = require('puppeteer/DeviceDescriptors');
const iPhone = DeviceDescriptors['iPhone 6'];
module.exports.addTests = function({testRunner, expect, product}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
const FFOX = product === 'firefox';
const CHROME = product === 'chromium';
describe('Page.click', () => {
it('should click the button', async({page, server}) => {
await page.goto(server.PREFIX + '/input/button.html');
await page.click('button');
expect(await page.evaluate(() => result)).toBe('Clicked');
});
it('should click offscreen buttons', async({page, server}) => {
await page.goto(server.PREFIX + '/offscreenbuttons.html');
const messages = [];
page.on('console', msg => messages.push(msg.text()));
for (let i = 0; i < 11; ++i) {
// We might've scrolled to click a button - reset to (0, 0).
await page.evaluate(() => window.scrollTo(0, 0));
await page.click(`#btn${i}`);
}
expect(messages).toEqual([
'button #0 clicked',
'button #1 clicked',
'button #2 clicked',
'button #3 clicked',
'button #4 clicked',
'button #5 clicked',
'button #6 clicked',
'button #7 clicked',
'button #8 clicked',
'button #9 clicked',
'button #10 clicked'
]);
});
it('should click wrapped links', async({page, server}) => {
await page.goto(server.PREFIX + '/wrappedlink.html');
await page.click('a');
expect(await page.evaluate(() => window.__clicked)).toBe(true);
});
it('should click on checkbox input and toggle', async({page, server}) => {
await page.goto(server.PREFIX + '/input/checkbox.html');
expect(await page.evaluate(() => result.check)).toBe(null);
await page.click('input#agree');
expect(await page.evaluate(() => result.check)).toBe(true);
expect(await page.evaluate(() => result.events)).toEqual([
'mouseover',
'mouseenter',
'mousemove',
'mousedown',
'mouseup',
'click',
'input',
'change',
]);
await page.click('input#agree');
expect(await page.evaluate(() => result.check)).toBe(false);
});
it('should click on checkbox label and toggle', async({page, server}) => {
await page.goto(server.PREFIX + '/input/checkbox.html');
expect(await page.evaluate(() => result.check)).toBe(null);
await page.click('label[for="agree"]');
expect(await page.evaluate(() => result.check)).toBe(true);
expect(await page.evaluate(() => result.events)).toEqual([
'click',
'input',
'change',
]);
await page.click('label[for="agree"]');
expect(await page.evaluate(() => result.check)).toBe(false);
});
it('should fail to click a missing button', async({page, server}) => {
await page.goto(server.PREFIX + '/input/button.html');
let error = null;
await page.click('button.does-not-exist').catch(e => error = e);
expect(error.message).toBe('No node found for selector: button.does-not-exist');
});
// @see https://github.com/GoogleChrome/puppeteer/issues/161
it('should not hang with touch-enabled viewports', async({page, server}) => {
await page.setViewport(iPhone.viewport);
await page.mouse.down();
await page.mouse.move(100, 10);
await page.mouse.up();
});
it('should click the button after navigation ', async({page, server}) => {
await page.goto(server.PREFIX + '/input/button.html');
await page.click('button');
await page.goto(server.PREFIX + '/input/button.html');
await page.click('button');
expect(await page.evaluate(() => result)).toBe('Clicked');
});
it('should scroll and click the button', async({page, server}) => {
await page.goto(server.PREFIX + '/input/scrollable.html');
await page.click('#button-5');
expect(await page.evaluate(() => document.querySelector('#button-5').textContent)).toBe('clicked');
await page.click('#button-80');
expect(await page.evaluate(() => document.querySelector('#button-80').textContent)).toBe('clicked');
});
it('should double click the button', async({page, server}) => {
await page.goto(server.PREFIX + '/input/button.html');
await page.evaluate(() => {
window.double = false;
const button = document.querySelector('button');
button.addEventListener('dblclick', event => {
window.double = true;
});
});
const button = await page.$('button');
await button.click({ clickCount: 2 });
expect(await page.evaluate('double')).toBe(true);
expect(await page.evaluate('result')).toBe('Clicked');
});
it('should click a partially obscured button', async({page, server}) => {
await page.goto(server.PREFIX + '/input/button.html');
await page.evaluate(() => {
const button = document.querySelector('button');
button.textContent = 'Some really long text that will go offscreen';
button.style.position = 'absolute';
button.style.left = '368px';
});
await page.click('button');
expect(await page.evaluate(() => window.result)).toBe('Clicked');
});
it('should select the text by triple clicking', async({page, server}) => {
await page.goto(server.PREFIX + '/input/textarea.html');
await page.focus('textarea');
const text = 'This is the text that we are going to try to select. Let\'s see how it goes.';
await page.keyboard.type(text);
await page.click('textarea');
await page.click('textarea', {clickCount: 2});
await page.click('textarea', {clickCount: 3});
expect(await page.evaluate(() => {
const textarea = document.querySelector('textarea');
return textarea.value.substring(textarea.selectionStart, textarea.selectionEnd);
})).toBe(text);
});
it('should fire contextmenu event on right click', async({page, server}) => {
await page.goto(server.PREFIX + '/input/scrollable.html');
await page.click('#button-8', {button: 'right'});
expect(await page.evaluate(() => document.querySelector('#button-8').textContent)).toBe('context menu');
});
it('should set modifier keys on click', async({page, server}) => {
await page.goto(server.PREFIX + '/input/scrollable.html');
await page.evaluate(() => document.querySelector('#button-3').addEventListener('mousedown', e => window.lastEvent = e, true));
const modifiers = {'Shift': 'shiftKey', 'Control': 'ctrlKey', 'Alt': 'altKey', 'Meta': 'metaKey'};
// In Firefox, the Meta modifier only exists on Mac
if (FFOX && os.platform() !== 'darwin')
delete modifiers['Meta'];
for (const modifier in modifiers) {
await page.keyboard.down(modifier);
await page.click('#button-3');
if (!(await page.evaluate(mod => window.lastEvent[mod], modifiers[modifier])))
throw new Error(modifiers[modifier] + ' should be true');
await page.keyboard.up(modifier);
}
await page.click('#button-3');
for (const modifier in modifiers) {
if ((await page.evaluate(mod => window.lastEvent[mod], modifiers[modifier])))
throw new Error(modifiers[modifier] + ' should be false');
}
});
// @see https://github.com/GoogleChrome/puppeteer/issues/206
it('should click links which cause navigation', async({page, server}) => {
await page.setContent(`<a href="${server.EMPTY_PAGE}">empty.html</a>`);
// This await should not hang.
await page.click('a');
});
it('should click the button inside an iframe', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await page.setContent('<div style="width:100px;height:100px">spacer</div>');
await utils.attachFrame(page, 'button-test', server.PREFIX + '/input/button.html');
const frame = page.frames()[1];
const button = await frame.$('button');
await button.click();
expect(await frame.evaluate(() => window.result)).toBe('Clicked');
});
it('should click the button with deviceScaleFactor set', async({page, server}) => {
await page.setViewport({width: 400, height: 400, deviceScaleFactor: 5});
expect(await page.evaluate(() => window.devicePixelRatio)).toBe(5);
await page.setContent('<div style="width:100px;height:100px">spacer</div>');
await utils.attachFrame(page, 'button-test', server.PREFIX + '/input/button.html');
const frame = page.frames()[1];
const button = await frame.$('button');
await button.click();
expect(await frame.evaluate(() => window.result)).toBe('Clicked');
});
});
};

View File

@ -1,39 +0,0 @@
const utils = require('./utils');
module.exports.addTests = function({testRunner, expect, product}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
const FFOX = product === 'firefox';
const CHROME = product === 'chromium';
describe('Page.Events.Dialog', function() {
it('should fire', async({page, server}) => {
page.on('dialog', dialog => {
expect(dialog.type()).toBe('alert');
expect(dialog.defaultValue()).toBe('');
expect(dialog.message()).toBe('yo');
dialog.accept();
});
await page.evaluate(() => alert('yo'));
});
it('should allow accepting prompts', async({page, server}) => {
page.on('dialog', dialog => {
expect(dialog.type()).toBe('prompt');
expect(dialog.defaultValue()).toBe('yes.');
expect(dialog.message()).toBe('question?');
dialog.accept('answer!');
});
const result = await page.evaluate(() => prompt('question?', 'yes.'));
expect(result).toBe('answer!');
});
it('should dismiss the prompt', async({page, server}) => {
page.on('dialog', dialog => {
dialog.dismiss();
});
const result = await page.evaluate(() => prompt('question?'));
expect(result).toBe(null);
});
});
};

View File

@ -1,103 +0,0 @@
/**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const utils = require('./utils');
module.exports.addTests = function({testRunner, expect, product}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
const FFOX = product === 'firefox';
const CHROME = product === 'chromium';
describe('JSHandle.asElement', function() {
it('should work', async({page, server}) => {
await page.setContent('<section>test</section>');
const handle = await page.evaluateHandle(() => document.querySelector('section'));
const element = handle.asElement();
expect(element).not.toBe(null);
});
it('should work with nullified Node', async({page, server}) => {
await page.setContent('<section>test</section>');
await page.evaluate(() => delete Node);
const handle = await page.evaluateHandle(() => document.querySelector('section'));
const element = handle.asElement();
expect(element).not.toBe(null);
});
it('should return null for non-elements', async({page, server}) => {
const handle = await page.evaluateHandle(() => ({foo: 'bar'}));
expect(handle.asElement()).toBe(null);
});
});
describe('ElementHandle.isIntersectingViewport', function() {
it('should work', async({page, server}) => {
await page.goto(server.PREFIX + '/offscreenbuttons.html');
for (let i = 0; i < 11; ++i) {
const button = await page.$('#btn' + i);
// All but last button are visible.
const visible = i < 10;
expect(await button.isIntersectingViewport()).toBe(visible);
}
});
});
describe('ElementHandle.boundingBox', function() {
it('should work', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html');
const elementHandle = await page.$('.box:nth-of-type(13)');
const box = await elementHandle.boundingBox();
expect(box).toEqual({ x: 100, y: 50, width: 50, height: 50 });
});
xit('should handle nested frames', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/frames/nested-frames.html');
const nestedFrame = page.frames()[1].childFrames()[1];
const elementHandle = await nestedFrame.$('div');
const box = await elementHandle.boundingBox();
await new Promise(() => {});
expect(box).toEqual({ x: 28, y: 260, width: 264, height: 18 });
});
it('should return null for invisible elements', async({page, server}) => {
await page.setContent('<div style="display:none">hi</div>');
const element = await page.$('div');
expect(await element.boundingBox()).toBe(null);
});
it('should force a layout', async({page, server}) => {
await page.setViewport({ width: 500, height: 500 });
await page.setContent('<div style="width: 100px; height: 100px">hello</div>');
const elementHandle = await page.$('div');
await page.evaluate(element => element.style.height = '200px', elementHandle);
const box = await elementHandle.boundingBox();
expect(box).toEqual({ x: 8, y: 8, width: 100, height: 200 });
});
it('should work with SVG nodes', async({page, server}) => {
await page.setContent(`
<svg xmlns="http://www.w3.org/2000/svg" width="500" height="500">
<rect id="theRect" x="30" y="50" width="200" height="300"></rect>
</svg>
`);
const element = await page.$('#therect');
const pptrBoundingBox = await element.boundingBox();
const webBoundingBox = await page.evaluate(e => {
const rect = e.getBoundingClientRect();
return {x: rect.x, y: rect.y, width: rect.width, height: rect.height};
}, element);
expect(pptrBoundingBox).toEqual(webBoundingBox);
});
});
};

View File

@ -1,86 +0,0 @@
/**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const DeviceDescriptors = require('puppeteer/DeviceDescriptors');
const iPhone = DeviceDescriptors['iPhone 6'];
const iPhoneLandscape = DeviceDescriptors['iPhone 6 landscape'];
module.exports.addTests = function({testRunner, expect, product}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
const FFOX = product === 'firefox';
const CHROME = product === 'chromium';
describe('Page.viewport', function() {
it('should get the proper viewport size', async({page, server}) => {
expect(page.viewport()).toEqual({width: 800, height: 600});
await page.setViewport({width: 123, height: 456});
expect(page.viewport()).toEqual({width: 123, height: 456});
});
it('should support mobile emulation', async({page, server}) => {
await page.goto(server.PREFIX + '/mobile.html');
expect(await page.evaluate(() => window.innerWidth)).toBe(800);
await page.setViewport(iPhone.viewport);
expect(await page.evaluate(() => window.innerWidth)).toBe(375);
await page.setViewport({width: 400, height: 300});
expect(await page.evaluate(() => window.innerWidth)).toBe(400);
});
it('should support touch emulation', async({page, server}) => {
await page.goto(server.PREFIX + '/mobile.html');
expect(await page.evaluate(() => 'ontouchstart' in window)).toBe(false);
await page.setViewport(iPhone.viewport);
expect(await page.evaluate(() => 'ontouchstart' in window)).toBe(true);
expect(await page.evaluate(dispatchTouch)).toBe('Received touch');
await page.setViewport({width: 100, height: 100});
expect(await page.evaluate(() => 'ontouchstart' in window)).toBe(false);
function dispatchTouch() {
let fulfill;
const promise = new Promise(x => fulfill = x);
window.ontouchstart = function(e) {
fulfill('Received touch');
};
window.dispatchEvent(new Event('touchstart'));
fulfill('Did not receive touch');
return promise;
}
});
it('should be detectable by Modernizr', async({page, server}) => {
await page.goto(server.PREFIX + '/detect-touch.html');
expect(await page.evaluate(() => document.body.textContent.trim())).toBe('NO');
await page.setViewport(iPhone.viewport);
await page.goto(server.PREFIX + '/detect-touch.html');
expect(await page.evaluate(() => document.body.textContent.trim())).toBe('YES');
});
it('should detect touch when applying viewport with touches', async({page, server}) => {
await page.setViewport({ width: 800, height: 600, hasTouch: true });
await page.addScriptTag({url: server.PREFIX + '/modernizr.js'});
expect(await page.evaluate(() => Modernizr.touchevents)).toBe(true);
});
xit('should support landscape emulation', async({page, server}) => {
await page.goto(server.PREFIX + '/mobile.html');
expect(await page.evaluate(() => screen.orientation.type)).toBe('portrait-primary');
await page.setViewport(iPhoneLandscape.viewport);
expect(await page.evaluate(() => screen.orientation.type)).toBe('landscape-primary');
await page.setViewport({width: 100, height: 100});
expect(await page.evaluate(() => screen.orientation.type)).toBe('portrait-primary');
});
});
};

View File

@ -1,181 +0,0 @@
/**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const utils = require('./utils');
module.exports.addTests = function({testRunner, expect, product}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
const FFOX = product === 'firefox';
const CHROME = product === 'chromium';
describe('Page.evaluate', function() {
it('should work', async({page, server}) => {
const result = await page.evaluate(() => 7 * 3);
expect(result).toBe(21);
});
it('should throw when evaluation triggers reload', async({page, server}) => {
let error = null;
await page.evaluate(() => {
location.reload();
return new Promise(resolve => {
setTimeout(() => resolve(1), 0);
});
}).catch(e => error = e);
expect(error.message).toContain('Protocol error');
});
it('should await promise', async({page, server}) => {
const result = await page.evaluate(() => Promise.resolve(8 * 7));
expect(result).toBe(56);
});
it('should reject promise with exception', async({page, server}) => {
let error = null;
await page.evaluate(() => not.existing.object.property).catch(e => error = e);
expect(error).toBeTruthy();
expect(error.message).toContain('not is not defined');
});
it('should support thrown strings as error messages', async({page, server}) => {
let error = null;
await page.evaluate(() => { throw 'qwerty'; }).catch(e => error = e);
expect(error).toBeTruthy();
expect(error.message).toContain('qwerty');
});
it('should support thrown numbers as error messages', async({page, server}) => {
let error = null;
await page.evaluate(() => { throw 100500; }).catch(e => error = e);
expect(error).toBeTruthy();
expect(error.message).toContain('100500');
});
it('should return complex objects', async({page, server}) => {
const object = {foo: 'bar!'};
const result = await page.evaluate(a => a, object);
expect(result).not.toBe(object);
expect(result).toEqual(object);
});
it('should transfer NaN', async({page, server}) => {
const result = await page.evaluate(a => a, NaN);
expect(Object.is(result, NaN)).toBe(true);
});
it('should transfer -0', async({page, server}) => {
const result = await page.evaluate(a => a, -0);
expect(Object.is(result, -0)).toBe(true);
});
it('should transfer Infinity', async({page, server}) => {
const result = await page.evaluate(a => a, Infinity);
expect(Object.is(result, Infinity)).toBe(true);
});
it('should transfer -Infinity', async({page, server}) => {
const result = await page.evaluate(a => a, -Infinity);
expect(Object.is(result, -Infinity)).toBe(true);
});
it('should transfer arrays', async({page, server}) => {
const result = await page.evaluate(a => a, [1, 2, 3]);
expect(result).toEqual([1,2,3]);
});
it('should transfer arrays as arrays, not objects', async({page, server}) => {
const result = await page.evaluate(a => Array.isArray(a), [1, 2, 3]);
expect(result).toBe(true);
});
it('should accept "undefined" as one of multiple parameters', async({page, server}) => {
const result = await page.evaluate((a, b) => Object.is(a, undefined) && Object.is(b, 'foo'), undefined, 'foo');
expect(result).toBe(true);
});
it('should properly serialize null fields', async({page}) => {
expect(await page.evaluate(() => ({a: undefined}))).toEqual({});
});
it('should return undefined for non-serializable objects', async({page, server}) => {
expect(await page.evaluate(() => window)).toBe(undefined);
});
xit('should return undefined for objects with symbols', async({page, server}) => {
expect(await page.evaluate(() => [Symbol('foo4')])).toBe(undefined);
});
it('should fail for circular object', async({page, server}) => {
const result = await page.evaluate(() => {
const a = {};
const b = {a};
a.b = b;
return a;
});
expect(result).toBe(undefined);
});
it('should accept a string', async({page, server}) => {
const result = await page.evaluate('1 + 2');
expect(result).toBe(3);
});
it('should accept a string with semi colons', async({page, server}) => {
const result = await page.evaluate('1 + 5;');
expect(result).toBe(6);
});
it('should accept a string with comments', async({page, server}) => {
const result = await page.evaluate('2 + 5;\n// do some math!');
expect(result).toBe(7);
});
it('should simulate a user gesture', async({page, server}) => {
const result = await page.evaluate(() => document.execCommand('copy'));
expect(result).toBe(true);
});
it('should evaluate in the page context', async({page, server}) => {
await page.goto(server.PREFIX + '/global-var.html');
expect(await page.evaluate('globalVar')).toBe(123);
});
it('should modify global environment', async({page}) => {
await page.evaluate(() => window.globalVar = 123);
expect(await page.evaluate('globalVar')).toBe(123);
});
});
describe('Frame.evaluate', function() {
it('should have different execution contexts', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE2);
expect(page.frames().length).toBe(2);
await page.frames()[0].evaluate(() => window.FOO = 'foo');
await page.frames()[1].evaluate(() => window.FOO = 'bar');
expect(await page.frames()[0].evaluate(() => window.FOO)).toBe('foo');
expect(await page.frames()[1].evaluate(() => window.FOO)).toBe('bar');
});
it('should have correct execution contexts', async({page, server}) => {
await page.goto(server.PREFIX + '/frames/one-frame.html');
expect(page.frames().length).toBe(2);
expect(await page.frames()[0].evaluate(() => document.body.textContent.trim())).toBe('');
expect(await page.frames()[1].evaluate(() => document.body.textContent.trim())).toBe(`Hi, I'm frame`);
});
});
describe('Page.evaluateOnNewDocument', function() {
it('should evaluate before anything else on the page', async({page, server}) => {
await page.evaluateOnNewDocument(function(){
window.injected = 123;
});
await page.goto(server.PREFIX + '/tamperable.html');
expect(await page.evaluate(() => window.result)).toBe(123);
});
it('should work with CSP', async({page, server}) => {
server.setCSP('/empty.html', 'script-src ' + server.PREFIX);
await page.evaluateOnNewDocument(function(){
window.injected = 123;
});
await page.goto(server.PREFIX + '/empty.html');
expect(await page.evaluate(() => window.injected)).toBe(123);
// Make sure CSP works.
await page.addScriptTag({content: 'window.e = 10;'}).catch(e => void e);
expect(await page.evaluate(() => window.e)).toBe(undefined);
});
});
};

View File

@ -1,24 +0,0 @@
module.exports.addTests = function({testRunner, expect, product}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
describe('Firefox-specific tests', function() {
describe('Browser.version', function() {
it('should return whether we are in headless', async({browser}) => {
const version = await browser.version();
expect(version.length).toBeGreaterThan(0);
expect(version.startsWith('Firefox/')).toBe(true);
});
});
describe('Browser.userAgent', function() {
it('should include WebKit', async({browser}) => {
const userAgent = await browser.userAgent();
expect(userAgent.length).toBeGreaterThan(0);
expect(userAgent).toContain('Gecko');
});
});
});
};

View File

@ -1,137 +0,0 @@
/**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const utils = require('./utils');
module.exports.addTests = function({testRunner, expect, product}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
const FFOX = product === 'firefox';
const CHROME = product === 'chromium';
describe('Frame Management', function() {
it('should handle nested frames', async({page, server}) => {
await page.goto(server.PREFIX + '/frames/nested-frames.html');
expect(utils.dumpFrames(page.mainFrame())).toEqual([
'http://localhost:<PORT>/frames/nested-frames.html',
' http://localhost:<PORT>/frames/two-frames.html (2frames)',
' http://localhost:<PORT>/frames/frame.html (uno)',
' http://localhost:<PORT>/frames/frame.html (dos)',
' http://localhost:<PORT>/frames/frame.html (aframe)'
]);
});
it('should send events when frames are manipulated dynamically', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
// validate frameattached events
const attachedFrames = [];
page.on('frameattached', frame => attachedFrames.push(frame));
await utils.attachFrame(page, 'frame1', '/frames/frame.html');
expect(attachedFrames.length).toBe(1);
expect(attachedFrames[0].url()).toContain('/frames/frame.html');
// validate framenavigated events
const navigatedFrames = [];
page.on('framenavigated', frame => navigatedFrames.push(frame));
await utils.navigateFrame(page, 'frame1', server.PREFIX + '/empty2.html');
expect(navigatedFrames.length).toBe(1);
expect(navigatedFrames[0].url()).toBe(server.PREFIX + '/empty2.html');
// validate framedetached events
const detachedFrames = [];
page.on('framedetached', frame => detachedFrames.push(frame));
await utils.detachFrame(page, 'frame1');
expect(detachedFrames.length).toBe(1);
expect(detachedFrames[0].isDetached()).toBe(true);
});
it('should send "framenavigated" when navigating on anchor URLs', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await Promise.all([
page.goto(server.EMPTY_PAGE + '#foo'),
utils.waitEvent(page, 'framenavigated')
]);
expect(page.url()).toBe(server.EMPTY_PAGE + '#foo');
});
it('should not send attach/detach events for main frame', async({page, server}) => {
let hasEvents = false;
page.on('frameattached', frame => hasEvents = true);
page.on('framedetached', frame => hasEvents = true);
await page.goto(server.EMPTY_PAGE);
expect(hasEvents).toBe(false);
});
it('should detach child frames on navigation', async({page, server}) => {
let attachedFrames = [];
let detachedFrames = [];
let navigatedFrames = [];
page.on('frameattached', frame => attachedFrames.push(frame));
page.on('framedetached', frame => detachedFrames.push(frame));
page.on('framenavigated', frame => navigatedFrames.push(frame));
await page.goto(server.PREFIX + '/frames/nested-frames.html');
expect(attachedFrames.length).toBe(4);
expect(detachedFrames.length).toBe(0);
expect(navigatedFrames.length).toBe(5);
attachedFrames = [];
detachedFrames = [];
navigatedFrames = [];
await page.goto(server.EMPTY_PAGE);
expect(attachedFrames.length).toBe(0);
expect(detachedFrames.length).toBe(4);
expect(navigatedFrames.length).toBe(1);
});
it('should support framesets', async({page, server}) => {
let attachedFrames = [];
let detachedFrames = [];
let navigatedFrames = [];
page.on('frameattached', frame => attachedFrames.push(frame));
page.on('framedetached', frame => detachedFrames.push(frame));
page.on('framenavigated', frame => navigatedFrames.push(frame));
await page.goto(server.PREFIX + '/frames/frameset.html');
expect(attachedFrames.length).toBe(4);
expect(detachedFrames.length).toBe(0);
expect(navigatedFrames.length).toBe(5);
attachedFrames = [];
detachedFrames = [];
navigatedFrames = [];
await page.goto(server.EMPTY_PAGE);
expect(attachedFrames.length).toBe(0);
expect(detachedFrames.length).toBe(4);
expect(navigatedFrames.length).toBe(1);
});
it('should report frame.name()', async({page, server}) => {
await utils.attachFrame(page, 'theFrameId', server.EMPTY_PAGE2);
await page.evaluate(url => {
const frame = document.createElement('iframe');
frame.name = 'theFrameName';
frame.src = url;
document.body.appendChild(frame);
return new Promise(x => frame.onload = x);
}, server.EMPTY_PAGE);
expect(page.frames()[0].name()).toBe('');
expect(page.frames()[1].name()).toBe('theFrameId');
expect(page.frames()[2].name()).toBe('theFrameName');
});
it('should report frame.parent()', async({page, server}) => {
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
await utils.attachFrame(page, 'frame2', server.EMPTY_PAGE);
expect(page.frames()[0].parentFrame()).toBe(null);
expect(page.frames()[1].parentFrame()).toBe(page.mainFrame());
expect(page.frames()[2].parentFrame()).toBe(page.mainFrame());
});
});
};

Binary file not shown.

Before

Width:  |  Height:  |  Size: 462 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 288 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 81 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 461 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 168 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 168 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 73 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.5 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 35 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 119 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 357 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 331 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 201 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 75 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.3 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 311 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 2.7 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 153 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 153 B

Binary file not shown.

Before

Width:  |  Height:  |  Size: 54 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 26 KiB

View File

@ -1,149 +0,0 @@
/**
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const path = require('path');
const fs = require('fs');
const Diff = require('text-diff');
const mime = require('mime');
const PNG = require('pngjs').PNG;
const jpeg = require('jpeg-js');
const pixelmatch = require('pixelmatch');
module.exports = {compare};
const GoldenComparators = {
'image/png': compareImages,
'image/jpeg': compareImages,
'text/plain': compareText
};
/**
* @param {?Object} actualBuffer
* @param {!Buffer} expectedBuffer
* @param {!string} mimeType
* @return {?{diff: (!Object:undefined), errorMessage: (string|undefined)}}
*/
function compareImages(actualBuffer, expectedBuffer, mimeType) {
if (!actualBuffer || !(actualBuffer instanceof Buffer))
return { errorMessage: 'Actual result should be Buffer.' };
const actual = mimeType === 'image/png' ? PNG.sync.read(actualBuffer) : jpeg.decode(actualBuffer);
const expected = mimeType === 'image/png' ? PNG.sync.read(expectedBuffer) : jpeg.decode(expectedBuffer);
if (expected.width !== actual.width || expected.height !== actual.height) {
return {
errorMessage: `Sizes differ: expected image ${expected.width}px X ${expected.height}px, but got ${actual.width}px X ${actual.height}px. `
};
}
const diff = new PNG({width: expected.width, height: expected.height});
const count = pixelmatch(expected.data, actual.data, diff.data, expected.width, expected.height, {threshold: 0.1});
return count > 0 ? { diff: PNG.sync.write(diff) } : null;
}
/**
* @param {?Object} actual
* @param {!Buffer} expectedBuffer
* @return {?{diff: (!Object:undefined), errorMessage: (string|undefined)}}
*/
function compareText(actual, expectedBuffer) {
if (typeof actual !== 'string')
return { errorMessage: 'Actual result should be string' };
const expected = expectedBuffer.toString('utf-8');
if (expected === actual)
return null;
const diff = new Diff();
const result = diff.main(expected, actual);
diff.cleanupSemantic(result);
let html = diff.prettyHtml(result);
const diffStylePath = path.join(__dirname, 'diffstyle.css');
html = `<link rel="stylesheet" href="file://${diffStylePath}">` + html;
return {
diff: html,
diffExtension: '.html'
};
}
/**
* @param {?Object} actual
* @param {string} goldenName
* @return {!{pass: boolean, message: (undefined|string)}}
*/
function compare(goldenPath, outputPath, actual, goldenName) {
goldenPath = path.normalize(goldenPath);
outputPath = path.normalize(outputPath);
const expectedPath = path.join(goldenPath, goldenName);
const actualPath = path.join(outputPath, goldenName);
const messageSuffix = 'Output is saved in "' + path.basename(outputPath + '" directory');
if (!fs.existsSync(expectedPath)) {
ensureOutputDir();
fs.writeFileSync(actualPath, actual);
return {
pass: false,
message: goldenName + ' is missing in golden results. ' + messageSuffix
};
}
const expected = fs.readFileSync(expectedPath);
const mimeType = mime.getType(goldenName);
const comparator = GoldenComparators[mimeType];
if (!comparator) {
return {
pass: false,
message: 'Failed to find comparator with type ' + mimeType + ': ' + goldenName
};
}
const result = comparator(actual, expected, mimeType);
if (!result)
return { pass: true };
ensureOutputDir();
if (goldenPath === outputPath) {
fs.writeFileSync(addSuffix(actualPath, '-actual'), actual);
} else {
fs.writeFileSync(actualPath, actual);
// Copy expected to the output/ folder for convenience.
fs.writeFileSync(addSuffix(actualPath, '-expected'), expected);
}
if (result.diff) {
const diffPath = addSuffix(actualPath, '-diff', result.diffExtension);
fs.writeFileSync(diffPath, result.diff);
}
let message = goldenName + ' mismatch!';
if (result.errorMessage)
message += ' ' + result.errorMessage;
return {
pass: false,
message: message + ' ' + messageSuffix
};
function ensureOutputDir() {
if (!fs.existsSync(outputPath))
fs.mkdirSync(outputPath);
}
}
/**
* @param {string} filePath
* @param {string} suffix
* @param {string=} customExtension
* @return {string}
*/
function addSuffix(filePath, suffix, customExtension) {
const dirname = path.dirname(filePath);
const ext = path.extname(filePath);
const name = path.basename(filePath, ext);
return path.join(dirname, name + suffix + (customExtension || ext));
}

View File

@ -1,37 +0,0 @@
/**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
module.exports.addTests = function({testRunner, expect, product}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
const FFOX = product === 'firefox';
const CHROME = product === 'chromium';
describe('Hover', function() {
it('should trigger hover state', async({page, server}) => {
await page.goto(server.PREFIX + '/input/scrollable.html');
await page.hover('#button-6');
expect(await page.evaluate(() => document.querySelector('button:hover').id)).toBe('button-6');
await page.hover('#button-2');
expect(await page.evaluate(() => document.querySelector('button:hover').id)).toBe('button-2');
await page.hover('#button-91');
expect(await page.evaluate(() => document.querySelector('button:hover').id)).toBe('button-91');
});
});
};

View File

@ -1,57 +0,0 @@
/**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
module.exports.addTests = function({testRunner, expect, product, puppeteer, defaultBrowserOptions}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
const FFOX = product === 'firefox';
const CHROME = product === 'chromium';
describe('ignoreHTTPSErrors', function() {
beforeAll(async state => {
const options = Object.assign({ignoreHTTPSErrors: true}, defaultBrowserOptions);
state.browser = await puppeteer.launch(options);
});
afterAll(async state => {
await state.browser.close();
delete state.browser;
});
beforeEach(async state => {
state.page = await state.browser.newPage();
});
afterEach(async state => {
await state.page.close();
delete state.page;
});
it('should work', async({page, httpsServer}) => {
let error = null;
await page.goto(httpsServer.EMPTY_PAGE).catch(e => error = e);
expect(error).toBe(null);
});
it('should work with mixed content', async({page, server, httpsServer}) => {
httpsServer.setRoute('/mixedcontent.html', (req, res) => {
res.end(`<iframe src=${server.EMPTY_PAGE}></iframe>`);
});
await page.goto(httpsServer.PREFIX + '/mixedcontent.html', {waitUntil: 'load'});
expect(page.frames().length).toBe(2);
// Make sure blocked iframe has functional execution context
// @see https://github.com/GoogleChrome/puppeteer/issues/2709
expect(await page.frames()[0].evaluate('1 + 2')).toBe(3);
expect(await page.frames()[1].evaluate('2 + 3')).toBe(5);
});
});
};

View File

@ -1,157 +0,0 @@
/**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const utils = require('./utils');
module.exports.addTests = function({testRunner, expect, product}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
const FFOX = product === 'firefox';
const CHROME = product === 'chromium';
describe('Page.evaluateHandle', function() {
it('should work', async({page, server}) => {
const windowHandle = await page.evaluateHandle(() => window);
expect(windowHandle).toBeTruthy();
});
it('should accept object handle as an argument', async({page, server}) => {
const navigatorHandle = await page.evaluateHandle(() => navigator);
const text = await page.evaluate(e => e.userAgent, navigatorHandle);
expect(text).toContain('Mozilla');
});
it('should accept object handle to primitive types', async({page, server}) => {
const aHandle = await page.evaluateHandle(() => 5);
const isFive = await page.evaluate(e => Object.is(e, 5), aHandle);
expect(isFive).toBeTruthy();
});
it('should accept object handle to unserializable value', async({page, server}) => {
const aHandle = await page.evaluateHandle(() => Infinity);
expect(await page.evaluate(e => Object.is(e, Infinity), aHandle)).toBe(true);
});
it('should use the same JS wrappers', async({page, server}) => {
const aHandle = await page.evaluateHandle(() => {
window.FOO = 123;
return window;
});
expect(await page.evaluate(e => e.FOO, aHandle)).toBe(123);
});
it('should work with primitives', async({page, server}) => {
const aHandle = await page.evaluateHandle(() => {
window.FOO = 123;
return window;
});
expect(await page.evaluate(e => e.FOO, aHandle)).toBe(123);
});
});
describe('JSHandle.jsonValue', function() {
it('should work', async({page, server}) => {
const aHandle = await page.evaluateHandle(() => ({foo: 'bar'}));
const json = await aHandle.jsonValue();
expect(json).toEqual({foo: 'bar'});
});
// This relies on Chrome's internal serialization. We can either repeat it
// in FFOX, or migrate to JSON.stringify() logic altogether.
(FFOX ? xit : it)('should not work with dates', async({page, server}) => {
const dateHandle = await page.evaluateHandle(() => new Date('2017-09-26T00:00:00.000Z'));
const json = await dateHandle.jsonValue();
expect(json).toEqual({});
});
it('should throw for circular objects', async({page, server}) => {
const windowHandle = await page.evaluateHandle('window');
let error = null;
await windowHandle.jsonValue().catch(e => error = e);
expect(error).not.toBe(null);
});
});
describe('JSHandle.toString', function() {
it('should work for primitives', async({page, server}) => {
const numberHandle = await page.evaluateHandle(() => 2);
expect(numberHandle.toString()).toBe('JSHandle:2');
const stringHandle = await page.evaluateHandle(() => 'a');
expect(stringHandle.toString()).toBe('JSHandle:a');
});
it('should work for complicated objects', async({page, server}) => {
const aHandle = await page.evaluateHandle(() => window);
expect(aHandle.toString()).toBe('JSHandle@object');
});
it('should work with different subtypes', async({page, server}) => {
expect((await page.evaluateHandle('(function(){})')).toString()).toBe('JSHandle@function');
expect((await page.evaluateHandle('12')).toString()).toBe('JSHandle:12');
expect((await page.evaluateHandle('true')).toString()).toBe('JSHandle:true');
expect((await page.evaluateHandle('undefined')).toString()).toBe('JSHandle:undefined');
expect((await page.evaluateHandle('"foo"')).toString()).toBe('JSHandle:foo');
expect((await page.evaluateHandle('Symbol()')).toString()).toBe('JSHandle@symbol');
expect((await page.evaluateHandle('new Map()')).toString()).toBe('JSHandle@map');
expect((await page.evaluateHandle('new Set()')).toString()).toBe('JSHandle@set');
expect((await page.evaluateHandle('[]')).toString()).toBe('JSHandle@array');
expect((await page.evaluateHandle('null')).toString()).toBe('JSHandle:null');
expect((await page.evaluateHandle('/foo/')).toString()).toBe('JSHandle@regexp');
expect((await page.evaluateHandle('document.body')).toString()).toBe('JSHandle@node');
expect((await page.evaluateHandle('new Date()')).toString()).toBe('JSHandle@date');
expect((await page.evaluateHandle('new WeakMap()')).toString()).toBe('JSHandle@weakmap');
expect((await page.evaluateHandle('new WeakSet()')).toString()).toBe('JSHandle@weakset');
expect((await page.evaluateHandle('new Error()')).toString()).toBe('JSHandle@error');
expect((await page.evaluateHandle('new Int32Array()')).toString()).toBe('JSHandle@typedarray');
expect((await page.evaluateHandle('new Proxy({}, {})')).toString()).toBe('JSHandle@proxy');
});
});
describe('JSHandle.getProperties', function() {
it('should work', async({page, server}) => {
const aHandle = await page.evaluateHandle(() => ({
foo: 'bar'
}));
const properties = await aHandle.getProperties();
const foo = properties.get('foo');
expect(foo).toBeTruthy();
expect(await foo.jsonValue()).toBe('bar');
});
it('should return even non-own properties', async({page, server}) => {
const aHandle = await page.evaluateHandle(() => {
class A {
constructor() {
this.a = '1';
}
}
class B extends A {
constructor() {
super();
this.b = '2';
}
}
return new B();
});
const properties = await aHandle.getProperties();
expect(await properties.get('a').jsonValue()).toBe('1');
expect(await properties.get('b').jsonValue()).toBe('2');
});
});
describe('JSHandle.getProperty', function() {
it('should work', async({page, server}) => {
const aHandle = await page.evaluateHandle(() => ({
one: 1,
two: 2,
three: 3
}));
const twoHandle = await aHandle.getProperty('two');
expect(await twoHandle.jsonValue()).toEqual(2);
});
});
};

View File

@ -1,193 +0,0 @@
/**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const utils = require('./utils');
const os = require('os');
module.exports.addTests = function({testRunner, expect, product}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
const FFOX = product === 'firefox';
const CHROME = product === 'chromium';
describe('Keyboard', function() {
it('should type into a textarea', async({page, server}) => {
await page.evaluate(() => {
const textarea = document.createElement('textarea');
document.body.appendChild(textarea);
textarea.focus();
});
const text = 'Hello world. I am the text that was typed!';
await page.keyboard.type(text);
expect(await page.evaluate(() => document.querySelector('textarea').value)).toBe(text);
});
it('should type emoji', async({page, server}) => {
await page.evaluate(() => {
const textarea = document.createElement('textarea');
document.body.appendChild(textarea);
textarea.focus();
});
await page.keyboard.type('👹 Tokyo street Japan 🇯🇵');
expect(await page.evaluate(() => document.querySelector('textarea').value)).toBe('👹 Tokyo street Japan 🇯🇵');
});
it('should type emoji', async({page, server}) => {
await page.goto(server.PREFIX + '/input/textarea.html');
await page.type('textarea', '👹 Tokyo street Japan 🇯🇵');
expect(await page.$eval('textarea', textarea => textarea.value)).toBe('👹 Tokyo street Japan 🇯🇵');
});
it('should type emoji into an iframe', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await utils.attachFrame(page, 'emoji-test', server.PREFIX + '/input/textarea.html');
const frame = page.frames()[1];
const textarea = await frame.$('textarea');
await textarea.type('👹 Tokyo street Japan 🇯🇵');
expect(await frame.$eval('textarea', textarea => textarea.value)).toBe('👹 Tokyo street Japan 🇯🇵');
});
it('should send a character with sendCharacter', async({page, server}) => {
await page.goto(server.PREFIX + '/input/textarea.html');
await page.focus('textarea');
await page.keyboard.sendCharacter('嗨');
expect(await page.evaluate(() => document.querySelector('textarea').value)).toBe('嗨');
await page.evaluate(() => window.addEventListener('keydown', e => e.preventDefault(), true));
await page.keyboard.sendCharacter('a');
expect(await page.evaluate(() => document.querySelector('textarea').value)).toBe('嗨a');
});
it('should press the metaKey', async({page}) => {
await page.evaluate(() => {
window.keyPromise = new Promise(resolve => document.addEventListener('keydown', event => resolve(event.key)));
});
await page.keyboard.press('Meta');
expect(await page.evaluate('keyPromise')).toBe(FFOX && os.platform() !== 'darwin' ? 'OS' : 'Meta');
});
xit('should report shiftKey', async({page, server}) => {
await page.goto(server.PREFIX + '/input/keyboard.html');
const keyboard = page.keyboard;
const codeForKey = {'Shift': 16, 'Alt': 18, 'Meta': 91, 'Control': 17};
// Firefox has no Meta modifier on Windows/Linux
if (FFOX && os.platform() !== 'darwin')
delete codeForKey['Meta'];
for (const modifierKey in codeForKey) {
await keyboard.down(modifierKey);
expect(await page.evaluate(() => getResult())).toBe('Keydown: ' + modifierKey + ' ' + modifierKey + 'Left ' + codeForKey[modifierKey] + ' [' + modifierKey + ']');
await keyboard.down('!');
// Shift+! will generate a keypress
if (modifierKey === 'Shift')
expect(await page.evaluate(() => getResult())).toBe('Keydown: ! Digit1 49 [' + modifierKey + ']\nKeypress: ! Digit1 33 33 [' + modifierKey + ']');
else
expect(await page.evaluate(() => getResult())).toBe('Keydown: ! Digit1 49 [' + modifierKey + ']');
await keyboard.up('!');
expect(await page.evaluate(() => getResult())).toBe('Keyup: ! Digit1 49 [' + modifierKey + ']');
await keyboard.up(modifierKey);
expect(await page.evaluate(() => getResult())).toBe('Keyup: ' + modifierKey + ' ' + modifierKey + 'Left ' + codeForKey[modifierKey] + ' []');
}
});
xit('should report multiple modifiers', async({page, server}) => {
await page.goto(server.PREFIX + '/input/keyboard.html');
const keyboard = page.keyboard;
await keyboard.down('Control');
expect(await page.evaluate(() => getResult())).toBe('Keydown: Control ControlLeft 17 [Control]');
await keyboard.down('Alt');
expect(await page.evaluate(() => getResult())).toBe('Keydown: Alt AltLeft 18 [Alt Control]');
await keyboard.down(';');
expect(await page.evaluate(() => getResult())).toBe('Keydown: ; Semicolon 186 [Alt Control]');
await keyboard.up(';');
expect(await page.evaluate(() => getResult())).toBe('Keyup: ; Semicolon 186 [Alt Control]');
await keyboard.up('Control');
expect(await page.evaluate(() => getResult())).toBe('Keyup: Control ControlLeft 17 [Alt]');
await keyboard.up('Alt');
expect(await page.evaluate(() => getResult())).toBe('Keyup: Alt AltLeft 18 []');
});
it('should send proper codes while typing', async({page, server}) => {
await page.goto(server.PREFIX + '/input/keyboard.html');
await page.keyboard.type('!');
expect(await page.evaluate(() => getResult())).toBe(
[ 'Keydown: ! Digit1 49 []',
'Keypress: ! Digit1 33 33 []',
'Keyup: ! Digit1 49 []'].join('\n'));
await page.keyboard.type('^');
expect(await page.evaluate(() => getResult())).toBe(
[ 'Keydown: ^ Digit6 54 []',
'Keypress: ^ Digit6 94 94 []',
'Keyup: ^ Digit6 54 []'].join('\n'));
});
it('should send proper codes while typing with shift', async({page, server}) => {
await page.goto(server.PREFIX + '/input/keyboard.html');
const keyboard = page.keyboard;
await keyboard.down('Shift');
await page.keyboard.type('~');
expect(await page.evaluate(() => getResult())).toBe(
[ 'Keydown: Shift ShiftLeft 16 [Shift]',
'Keydown: ~ Backquote 192 [Shift]', // 192 is ` keyCode
'Keypress: ~ Backquote 126 126 [Shift]', // 126 is ~ charCode
'Keyup: ~ Backquote 192 [Shift]'].join('\n'));
await keyboard.up('Shift');
});
it('should not type canceled events', async({page, server}) => {
await page.goto(server.PREFIX + '/input/textarea.html');
await page.focus('textarea');
await page.evaluate(() => {
window.addEventListener('keydown', event => {
event.stopPropagation();
event.stopImmediatePropagation();
if (event.key === 'l')
event.preventDefault();
if (event.key === 'o')
event.preventDefault();
}, false);
});
await page.keyboard.type('Hello World!');
expect(await page.evaluate(() => textarea.value)).toBe('He Wrd!');
});
it('should specify repeat property', async({page, server}) => {
await page.goto(server.PREFIX + '/input/textarea.html');
await page.focus('textarea');
await page.evaluate(() => document.querySelector('textarea').addEventListener('keydown', e => window.lastEvent = e, true));
await page.keyboard.down('a');
expect(await page.evaluate(() => window.lastEvent.repeat)).toBe(false);
await page.keyboard.press('a');
expect(await page.evaluate(() => window.lastEvent.repeat)).toBe(true);
await page.keyboard.down('b');
expect(await page.evaluate(() => window.lastEvent.repeat)).toBe(false);
await page.keyboard.down('b');
expect(await page.evaluate(() => window.lastEvent.repeat)).toBe(true);
await page.keyboard.up('a');
await page.keyboard.down('a');
expect(await page.evaluate(() => window.lastEvent.repeat)).toBe(false);
});
it('should type all kinds of characters', async({page, server}) => {
await page.goto(server.PREFIX + '/input/textarea.html');
await page.focus('textarea');
const text = 'This text goes onto two lines.\nThis character is 嗨.';
await page.keyboard.type(text);
expect(await page.evaluate('result')).toBe(text);
});
it('should throw on unknown keys', async({page, server}) => {
let error = await page.keyboard.press('NotARealKey').catch(e => e);
expect(error.message).toBe('Unknown key: "NotARealKey"');
error = await page.keyboard.press('ё').catch(e => e);
expect(error && error.message).toBe('Unknown key: "ё"');
error = await page.keyboard.press('😊').catch(e => e);
expect(error && error.message).toBe('Unknown key: "😊"');
});
});
};

View File

@ -1,56 +0,0 @@
/**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const fs = require('fs');
module.exports.addTests = function({testRunner, expect, product, puppeteer, defaultBrowserOptions}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
const FFOX = product === 'firefox';
const CHROME = product === 'chromium';
describe('Launcher.executablePath', function() {
it('should work', async({server}) => {
const executablePath = puppeteer.executablePath();
expect(fs.existsSync(executablePath)).toBe(true);
});
});
describe('Launcher.launch', () => {
it('should set the default viewport', async() => {
const options = Object.assign({}, defaultBrowserOptions, {
defaultViewport: {
width: 456,
height: 789
}
});
const browser = await puppeteer.launch(options);
const page = await browser.newPage();
expect(await page.evaluate('window.innerWidth')).toBe(456);
expect(await page.evaluate('window.innerHeight')).toBe(789);
await browser.close();
});
it('should disable the default viewport', async() => {
const options = Object.assign({}, defaultBrowserOptions, {
defaultViewport: null
});
const browser = await puppeteer.launch(options);
const page = await browser.newPage();
expect(page.viewport()).toBe(null);
await browser.close();
});
});
}

View File

@ -1,108 +0,0 @@
/**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
module.exports.addTests = function({testRunner, expect, product}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
const FFOX = product === 'firefox';
const CHROME = product === 'chromium';
describe('Mouse', function() {
it('should click the document', async({page, server}) => {
await page.evaluate(() => {
window.clickPromise = new Promise(resolve => {
document.addEventListener('click', event => {
resolve({
type: event.type,
detail: event.detail,
clientX: event.clientX,
clientY: event.clientY,
isTrusted: event.isTrusted,
button: event.button
});
});
});
});
await page.mouse.click(50, 60);
const event = await page.evaluate(() => window.clickPromise);
expect(event.type).toBe('click');
expect(event.detail).toBe(1);
expect(event.clientX).toBe(50);
expect(event.clientY).toBe(60);
expect(event.isTrusted).toBe(true);
expect(event.button).toBe(0);
});
it('should resize the textarea', async({page, server}) => {
await page.goto(server.PREFIX + '/input/textarea.html');
const {x, y, width, height} = await page.evaluate(dimensions);
const mouse = page.mouse;
await mouse.move(x + width - 4, y + height - 4);
await mouse.down();
await mouse.move(x + width + 100, y + height + 100);
await mouse.up();
const newDimensions = await page.evaluate(dimensions);
expect(newDimensions.width).toBe(Math.round(width + 104));
expect(newDimensions.height).toBe(Math.round(height + 104));
});
it('should select the text with mouse', async({page, server}) => {
await page.goto(server.PREFIX + '/input/textarea.html');
await page.focus('textarea');
const text = 'This is the text that we are going to try to select. Let\'s see how it goes.';
await page.keyboard.type(text);
// Firefox needs an extra frame here after typing or it will fail to set the scrollTop
await page.evaluate(() => new Promise(requestAnimationFrame));
await page.evaluate(() => document.querySelector('textarea').scrollTop = 0);
const {x, y} = await page.evaluate(dimensions);
await page.mouse.move(x + 2,y + 2);
await page.mouse.down();
await page.mouse.move(200,100);
await page.mouse.up();
expect(await page.evaluate(() => {
const textarea = document.querySelector('textarea');
return textarea.value.substring(textarea.selectionStart, textarea.selectionEnd);
})).toBe(text);
});
it('should tween mouse movement', async({page, server}) => {
await page.mouse.move(100, 100);
await page.evaluate(() => {
window.result = [];
document.addEventListener('mousemove', event => {
window.result.push([event.clientX, event.clientY]);
});
});
await page.mouse.move(200, 300, {steps: 5});
expect(await page.evaluate('result')).toEqual([
[120, 140],
[140, 180],
[160, 220],
[180, 260],
[200, 300]
]);
});
});
};
function dimensions() {
const rect = document.querySelector('textarea').getBoundingClientRect();
return {
x: rect.left,
y: rect.top,
width: rect.width,
height: rect.height
};
}

View File

@ -1,285 +0,0 @@
/**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const utils = require('./utils');
module.exports.addTests = function({testRunner, expect, product}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
const FFOX = product === 'firefox';
const CHROME = product === 'chromium';
describe('Page.goto', function () {
it('should work', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
expect(page.url()).toBe(server.EMPTY_PAGE);
});
it('should work with anchor navigation', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
expect(page.url()).toBe(server.EMPTY_PAGE);
await page.goto(server.EMPTY_PAGE + '#foo');
expect(page.url()).toBe(server.EMPTY_PAGE + '#foo');
await page.goto(server.EMPTY_PAGE + '#bar');
expect(page.url()).toBe(server.EMPTY_PAGE + '#bar');
});
it('should navigate to about:blank', async({page, server}) => {
await page.goto('about:blank');
expect(page.url()).toBe('about:blank');
});
it('should work with redirects', async({page, server}) => {
server.setRedirect('/redirect/1.html', '/redirect/2.html');
server.setRedirect('/redirect/2.html', '/empty.html');
await page.goto(server.PREFIX + '/redirect/1.html');
expect(page.url()).toBe(server.EMPTY_PAGE);
});
it('should work with subframes return 204', async({page, server}) => {
server.setRoute('/frames/frame.html', (req, res) => {
res.statusCode = 204;
res.end();
});
await page.goto(server.PREFIX + '/frames/one-frame.html');
});
it('should fail when server returns 204', async({page, server}) => {
server.setRoute('/empty.html', (req, res) => {
res.statusCode = 204;
res.end();
});
let error = null;
await page.goto(server.EMPTY_PAGE).catch(e => error = e);
expect(error).not.toBe(null);
expect(error.message).toContain('ABORTED');
});
it('should work when page calls history API in beforeunload', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await page.evaluate(() => {
window.addEventListener('beforeunload', () => history.replaceState(null, 'initial', window.location.href), false);
});
await page.goto(server.PREFIX + '/grid.html');
});
it('should fail when navigating to bad url', async({page, server}) => {
let error = null;
await page.goto('asdfasdf').catch(e => error = e);
expect(error).not.toBe(null);
});
it('should fail when navigating to bad url', async({page, server}) => {
let error = null;
await page.goto('asdf').catch(e => error = e);
expect(error).not.toBe(null);
});
it('should fail when navigating to bad SSL', async({page, httpsServer}) => {
let error = null;
await page.goto(httpsServer.EMPTY_PAGE).catch(e => error = e);
expect(error).not.toBe(null);
});
it('should fail when navigating to bad SSL after redirects', async({page, server, httpsServer}) => {
httpsServer.setRedirect('/redirect/1.html', '/redirect/2.html');
httpsServer.setRedirect('/redirect/2.html', '/empty.html');
let error = null;
await page.goto(httpsServer.PREFIX + '/redirect/1.html').catch(e => error = e);
expect(error).not.toBe(null);
});
it('should fail when main resources failed to load', async({page, server}) => {
let error = null;
await page.goto('http://localhost:44123/non-existing-url').catch(e => error = e);
expect(error).not.toBe(null);
});
it('should fail when exceeding maximum navigation timeout', async({page, server}) => {
// Hang for request to the empty.html
server.setRoute('/empty.html', (req, res) => { });
let error = null;
await page.goto(server.PREFIX + '/empty.html', {timeout: 1}).catch(e => error = e);
expect(error.message).toContain('Navigation Timeout Exceeded: 1ms');
});
it('should disable timeout when its set to 0', async({page, server}) => {
await page.goto(server.PREFIX + '/grid.html', {timeout: 0});
});
it('should work when navigating to data url', async({page, server}) => {
await page.goto('data:text/html,hello');
});
it('should work when navigating to 404', async({page, server}) => {
await page.goto(server.PREFIX + '/not-found');
});
it('should not leak listeners during navigation', async({page, server}) => {
let warning = null;
const warningHandler = w => warning = w;
process.on('warning', warningHandler);
for (let i = 0; i < 20; ++i)
await page.goto(server.EMPTY_PAGE);
process.removeListener('warning', warningHandler);
expect(warning).toBe(null);
});
it('should fail when navigating and show the url at the error message', async function({page, server, httpsServer}) {
const url = httpsServer.PREFIX + '/redirect/1.html';
let error = null;
try {
await page.goto(url);
} catch (e) {
error = e;
}
expect(error.message).toContain(url);
});
});
describe('Page.waitForNavigation', function() {
it('should work', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
const [response] = await Promise.all([
page.waitForNavigation(),
page.evaluate(url => window.location.href = url, server.PREFIX + '/grid.html')
]);
expect(page.url()).toBe(server.PREFIX + '/grid.html');
});
it('should work with both domcontentloaded and load', async({page, server}) => {
let response = null;
server.setRoute('/one-style.css', (req, res) => response = res);
const navigationPromise = page.goto(server.PREFIX + '/one-style.html');
const domContentLoadedPromise = page.waitForNavigation({
waitUntil: 'domcontentloaded'
});
let bothFired = false;
const bothFiredPromise = page.waitForNavigation({
waitUntil: ['load', 'domcontentloaded']
}).then(() => bothFired = true);
await server.waitForRequest('/one-style.css');
await domContentLoadedPromise;
expect(bothFired).toBe(false);
response.end();
await bothFiredPromise;
await navigationPromise;
});
it('should work with clicking on anchor links', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await page.setContent(`<a href='#foobar'>foobar</a>`);
await Promise.all([
page.waitForNavigation(),
page.click('a'),
]);
expect(page.url()).toBe(server.EMPTY_PAGE + '#foobar');
});
it('should work with history.pushState()', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await page.setContent(`
<a onclick='javascript:pushState()'>SPA</a>
<script>
function pushState() { history.pushState({}, '', 'wow.html') }
</script>
`);
await Promise.all([
page.waitForNavigation(),
page.click('a'),
]);
expect(page.url()).toBe(server.PREFIX + '/wow.html');
});
it('should work with history.replaceState()', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await page.setContent(`
<a onclick='javascript:replaceState()'>SPA</a>
<script>
function replaceState() { history.replaceState({}, '', '/replaced.html') }
</script>
`);
await Promise.all([
page.waitForNavigation(),
page.click('a'),
]);
expect(page.url()).toBe(server.PREFIX + '/replaced.html');
});
xit('should work with DOM history.back()/history.forward()', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await page.setContent(`
<a id=back onclick='javascript:goBack()'>back</a>
<a id=forward onclick='javascript:goForward()'>forward</a>
<script>
function goBack() { history.back(); }
function goForward() { history.forward(); }
history.pushState({}, '', '/first.html');
history.pushState({}, '', '/second.html');
</script>
`);
expect(page.url()).toBe(server.PREFIX + '/second.html');
await Promise.all([
page.waitForNavigation(),
page.click('a#back'),
]);
expect(page.url()).toBe(server.PREFIX + '/first.html');
await Promise.all([
page.waitForNavigation(),
page.click('a#forward'),
]);
expect(page.url()).toBe(server.PREFIX + '/second.html');
});
it('should work when subframe issues window.stop()', async({page, server}) => {
server.setRoute('/frames/style.css', (req, res) => {});
const navigationPromise = page.goto(server.PREFIX + '/frames/one-frame.html');
const frame = await utils.waitEvent(page, 'frameattached');
await new Promise(fulfill => {
page.on('framenavigated', f => {
if (f === frame)
fulfill();
});
});
await Promise.all([
frame.evaluate(() => window.stop()),
navigationPromise
]);
});
});
describe('Page.goBack + Page.goForward', function() {
it('should work', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await page.goto(server.PREFIX + '/grid.html');
await page.goBack();
expect(page.url()).toBe(server.EMPTY_PAGE);
await page.goForward();
expect(page.url()).toContain('/grid.html');
await page.goForward();
expect(page.url()).toContain('/grid.html');
});
it('should work with HistoryAPI', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await page.evaluate(() => {
history.pushState({}, '', '/first.html');
history.pushState({}, '', '/second.html');
});
expect(page.url()).toBe(server.PREFIX + '/second.html');
await page.goBack();
expect(page.url()).toBe(server.PREFIX + '/first.html');
await page.goBack();
expect(page.url()).toBe(server.EMPTY_PAGE);
await page.goForward();
expect(page.url()).toBe(server.PREFIX + '/first.html');
});
});
describe('Page.reload', function() {
it('should work', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await page.evaluate(() => window._foo = 10);
await page.reload();
expect(await page.evaluate(() => window._foo)).toBe(undefined);
});
});
};

View File

@ -1,403 +0,0 @@
/**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const utils = require('./utils');
const path = require('path');
module.exports.addTests = function({testRunner, expect, product}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
const FFOX = product === 'firefox';
const CHROME = product === 'chromium';
describe('Page.Events.DOMContentLoaded', function() {
it('should fire when expected', async({page, server}) => {
await Promise.all([
page.goto('about:blank'),
utils.waitEvent(page, 'domcontentloaded'),
]);
});
});
describe('Page.Events.Load', function() {
it('should fire when expected', async({page, server}) => {
await Promise.all([
page.goto('about:blank'),
utils.waitEvent(page, 'load'),
]);
});
});
describe('Page.Events.PageError', function() {
it('should fire', async({page, server}) => {
let error = null;
page.once('pageerror', e => error = e);
await Promise.all([
page.goto(server.PREFIX + '/error.html'),
utils.waitEvent(page, 'pageerror')
]);
expect(error.message).toContain('Fancy');
});
});
describe('Page.close', function() {
it('should reject all promises when page is closed', async({browser}) => {
const newPage = await browser.newPage();
const neverResolves = newPage.evaluate(() => new Promise(r => {}));
newPage.close();
let error = null;
await neverResolves.catch(e => error = e);
expect(error).not.toBe(null);
});
it('should not be visible in browser.pages', async({browser}) => {
const newPage = await browser.newPage();
expect(await browser.pages()).toContain(newPage);
await newPage.close();
expect(await browser.pages()).not.toContain(newPage);
});
it('should set the page close state', async({browser}) => {
const newPage = await browser.newPage();
expect(newPage.isClosed()).toBe(false);
await newPage.close();
expect(newPage.isClosed()).toBe(true);
});
it('should work with page.close', async function({ page, context, server }) {
const newPage = await context.newPage();
const closedPromise = new Promise(x => newPage.on('close', x));
await newPage.close();
await closedPromise;
});
});
describe('Page.Events.Console', function() {
it('should work', async({page, server}) => {
let message = null;
page.once('console', m => message = m);
await Promise.all([
page.evaluate(() => console.log('hello', 5, {foo: 'bar'})),
utils.waitEvent(page, 'console')
]);
expect(message.text()).toEqual('hello 5 JSHandle@object');
expect(message.type()).toEqual('log');
expect(await message.args()[0].jsonValue()).toEqual('hello');
expect(await message.args()[1].jsonValue()).toEqual(5);
expect(await message.args()[2].jsonValue()).toEqual({foo: 'bar'});
});
it('should work for different console API calls', async({page, server}) => {
const messages = [];
page.on('console', msg => messages.push(msg));
// All console events will be reported before `page.evaluate` is finished.
await page.evaluate(() => {
// A pair of time/timeEnd generates only one Console API call.
console.time('calling console.time');
console.timeEnd('calling console.time');
console.trace('calling console.trace');
console.dir('calling console.dir');
console.warn('calling console.warn');
console.error('calling console.error');
console.log(Promise.resolve('should not wait until resolved!'));
});
expect(messages.map(msg => msg.type())).toEqual([
'timeEnd', 'trace', 'dir', 'warning', 'error', 'log'
]);
expect(messages[0].text()).toContain('calling console.time');
expect(messages.slice(1).map(msg => msg.text())).toEqual([
'calling console.trace',
'calling console.dir',
'calling console.warn',
'calling console.error',
'JSHandle@promise',
]);
});
it('should not fail for window object', async({page, server}) => {
let message = null;
page.once('console', msg => message = msg);
await Promise.all([
page.evaluate(() => console.error(window)),
utils.waitEvent(page, 'console')
]);
expect(message.text()).toBe('JSHandle@object');
});
});
describe('Page.content / Page.setContent', function() {
const expectedOutput = '<html><head></head><body><div>hello</div></body></html>';
it('should work', async({page, server}) => {
await page.setContent('<div>hello</div>');
const result = await page.content();
expect(result).toBe(expectedOutput);
});
it('should work with doctype', async({page, server}) => {
const doctype = '<!DOCTYPE html>';
await page.setContent(`${doctype}<div>hello</div>`);
const result = await page.content();
expect(result).toBe(`${doctype}${expectedOutput}`);
});
it('should work with HTML 4 doctype', async({page, server}) => {
const doctype = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" ' +
'"http://www.w3.org/TR/html4/strict.dtd">';
await page.setContent(`${doctype}<div>hello</div>`);
const result = await page.content();
expect(result).toBe(`${doctype}${expectedOutput}`);
});
});
describe('Page.addScriptTag', function() {
it('should throw an error if no options are provided', async({page, server}) => {
let error = null;
try {
await page.addScriptTag('/injectedfile.js');
} catch (e) {
error = e;
}
expect(error.message).toBe('Provide an object with a `url`, `path` or `content` property');
});
it('should work with a url', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
const scriptHandle = await page.addScriptTag({ url: '/injectedfile.js' });
expect(scriptHandle.asElement()).not.toBeNull();
expect(await page.evaluate(() => __injected)).toBe(42);
});
it('should work with a url and type=module', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await page.addScriptTag({ url: '/es6/es6import.js', type: 'module' });
expect(await page.evaluate(() => __es6injected)).toBe(42);
});
it('should work with a path and type=module', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await page.addScriptTag({ path: path.join(__dirname, 'assets/es6/es6pathimport.js'), type: 'module' });
await page.waitForFunction('window.__es6injected');
expect(await page.evaluate(() => __es6injected)).toBe(42);
});
it('should work with a content and type=module', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await page.addScriptTag({ content: `import num from '/es6/es6module.js';window.__es6injected = num;`, type: 'module' });
await page.waitForFunction('window.__es6injected');
expect(await page.evaluate(() => __es6injected)).toBe(42);
});
it('should throw an error if loading from url fail', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
let error = null;
try {
await page.addScriptTag({ url: '/nonexistfile.js' });
} catch (e) {
error = e;
}
expect(error.message).toBe('Loading script from /nonexistfile.js failed');
});
it('should work with a path', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
const scriptHandle = await page.addScriptTag({ path: path.join(__dirname, 'assets/injectedfile.js') });
expect(scriptHandle.asElement()).not.toBeNull();
expect(await page.evaluate(() => __injected)).toBe(42);
});
it('should include sourcemap when path is provided', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await page.addScriptTag({ path: path.join(__dirname, 'assets/injectedfile.js') });
const result = await page.evaluate(() => __injectedError.stack);
expect(result).toContain(path.join('assets', 'injectedfile.js'));
});
it('should work with content', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
const scriptHandle = await page.addScriptTag({ content: 'window.__injected = 35;' });
expect(scriptHandle.asElement()).not.toBeNull();
expect(await page.evaluate(() => __injected)).toBe(35);
});
xit('should throw when added with content to the CSP page', async({page, server}) => {
await page.goto(server.PREFIX + '/csp.html');
let error = null;
await page.addScriptTag({ content: 'window.__injected = 35;' }).catch(e => error = e);
expect(error).toBeTruthy();
});
it('should throw when added with URL to the CSP page', async({page, server}) => {
await page.goto(server.PREFIX + '/csp.html');
let error = null;
await page.addScriptTag({ url: server.CROSS_PROCESS_PREFIX + '/injectedfile.js' }).catch(e => error = e);
expect(error).toBeTruthy();
});
});
describe('Page.addStyleTag', function() {
it('should throw an error if no options are provided', async({page, server}) => {
let error = null;
try {
await page.addStyleTag('/injectedstyle.css');
} catch (e) {
error = e;
}
expect(error.message).toBe('Provide an object with a `url`, `path` or `content` property');
});
it('should work with a url', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
const styleHandle = await page.addStyleTag({ url: '/injectedstyle.css' });
expect(styleHandle.asElement()).not.toBeNull();
expect(await page.evaluate(`window.getComputedStyle(document.querySelector('body')).getPropertyValue('background-color')`)).toBe('rgb(255, 0, 0)');
});
it('should throw an error if loading from url fail', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
let error = null;
try {
await page.addStyleTag({ url: '/nonexistfile.js' });
} catch (e) {
error = e;
}
expect(error.message).toBe('Loading style from /nonexistfile.js failed');
});
it('should work with a path', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
const styleHandle = await page.addStyleTag({ path: path.join(__dirname, 'assets/injectedstyle.css') });
expect(styleHandle.asElement()).not.toBeNull();
expect(await page.evaluate(`window.getComputedStyle(document.querySelector('body')).getPropertyValue('background-color')`)).toBe('rgb(255, 0, 0)');
});
it('should include sourcemap when path is provided', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await page.addStyleTag({ path: path.join(__dirname, 'assets/injectedstyle.css') });
const styleHandle = await page.$('style');
const styleContent = await page.evaluate(style => style.innerHTML, styleHandle);
expect(styleContent).toContain(path.join('assets', 'injectedstyle.css'));
});
it('should work with content', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
const styleHandle = await page.addStyleTag({ content: 'body { background-color: green; }' });
expect(styleHandle.asElement()).not.toBeNull();
expect(await page.evaluate(`window.getComputedStyle(document.querySelector('body')).getPropertyValue('background-color')`)).toBe('rgb(0, 128, 0)');
});
xit('should throw when added with content to the CSP page', async({page, server}) => {
await page.goto(server.PREFIX + '/csp.html');
let error = null;
await page.addStyleTag({ content: 'body { background-color: green; }' }).catch(e => error = e);
expect(error).toBeTruthy();
});
it('should throw when added with URL to the CSP page', async({page, server}) => {
await page.goto(server.PREFIX + '/csp.html');
let error = null;
await page.addStyleTag({ url: server.CROSS_PROCESS_PREFIX + '/injectedstyle.css' }).catch(e => error = e);
expect(error).toBeTruthy();
});
});
describe('Page.title', function() {
it('should return the page title', async({page, server}) => {
await page.goto(server.PREFIX + '/title.html');
expect(await page.title()).toBe('Woof-Woof');
});
});
describe('Page.select', function() {
it('should select single option', async({page, server}) => {
await page.goto(server.PREFIX + '/input/select.html');
await page.select('select', 'blue');
expect(await page.evaluate(() => result.onInput)).toEqual(['blue']);
expect(await page.evaluate(() => result.onChange)).toEqual(['blue']);
});
it('should select only first option', async({page, server}) => {
await page.goto(server.PREFIX + '/input/select.html');
await page.select('select', 'blue', 'green', 'red');
expect(await page.evaluate(() => result.onInput)).toEqual(['blue']);
expect(await page.evaluate(() => result.onChange)).toEqual(['blue']);
});
it('should select multiple options', async({page, server}) => {
await page.goto(server.PREFIX + '/input/select.html');
await page.evaluate(() => makeMultiple());
await page.select('select', 'blue', 'green', 'red');
expect(await page.evaluate(() => result.onInput)).toEqual(['blue', 'green', 'red']);
expect(await page.evaluate(() => result.onChange)).toEqual(['blue', 'green', 'red']);
});
it('should respect event bubbling', async({page, server}) => {
await page.goto(server.PREFIX + '/input/select.html');
await page.select('select', 'blue');
expect(await page.evaluate(() => result.onBubblingInput)).toEqual(['blue']);
expect(await page.evaluate(() => result.onBubblingChange)).toEqual(['blue']);
});
it('should throw when element is not a <select>', async({page, server}) => {
let error = null;
await page.goto(server.PREFIX + '/input/select.html');
await page.select('body', '').catch(e => error = e);
expect(error.message).toContain('Element is not a <select> element.');
});
it('should return [] on no matched values', async({page, server}) => {
await page.goto(server.PREFIX + '/input/select.html');
const result = await page.select('select','42','abc');
expect(result).toEqual([]);
});
it('should return an array of matched values', async({page, server}) => {
await page.goto(server.PREFIX + '/input/select.html');
await page.evaluate(() => makeMultiple());
const result = await page.select('select','blue','black','magenta');
expect(result.reduce((accumulator,current) => ['blue', 'black', 'magenta'].includes(current) && accumulator, true)).toEqual(true);
});
it('should return an array of one element when multiple is not set', async({page, server}) => {
await page.goto(server.PREFIX + '/input/select.html');
const result = await page.select('select','42','blue','black','magenta');
expect(result.length).toEqual(1);
});
it('should return [] on no values',async({page, server}) => {
await page.goto(server.PREFIX + '/input/select.html');
const result = await page.select('select');
expect(result).toEqual([]);
});
it('should deselect all options when passed no values for a multiple select',async({page, server}) => {
await page.goto(server.PREFIX + '/input/select.html');
await page.evaluate(() => makeMultiple());
await page.select('select','blue','black','magenta');
await page.select('select');
expect(await page.$eval('select', select => Array.from(select.options).every(option => !option.selected))).toEqual(true);
});
it('should deselect all options when passed no values for a select without multiple',async({page, server}) => {
await page.goto(server.PREFIX + '/input/select.html');
await page.select('select','blue','black','magenta');
await page.select('select');
expect(await page.$eval('select', select => Array.from(select.options).every(option => !option.selected))).toEqual(true);
});
it('should throw if passed in non-strings', async({page, server}) => {
await page.setContent('<select><option value="12"/></select>');
let error = null;
try {
await page.select('select', 12);
} catch (e) {
error = e;
}
expect(error.message).toContain('Values must be strings');
});
// @see https://github.com/GoogleChrome/puppeteer/issues/3327
xit('should work when re-defining top-level Event class', async({page, server}) => {
await page.goto(server.PREFIX + '/input/select.html');
await page.evaluate(() => window.Event = null);
await page.select('select', 'blue');
expect(await page.evaluate(() => result.onInput)).toEqual(['blue']);
expect(await page.evaluate(() => result.onChange)).toEqual(['blue']);
});
});
};

View File

@ -1,104 +0,0 @@
/**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const path = require('path');
const GoldenUtils = require('./golden-utils');
const {Matchers} = require('@pptr/testrunner');
module.exports.addTests = ({testRunner, product, puppeteer}) => testRunner.describe(product, () => {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
const GOLDEN_DIR = path.join(__dirname, 'golden-' + product);
const OUTPUT_DIR = path.join(__dirname, 'output-' + product);
const {expect} = new Matchers({
toBeGolden: GoldenUtils.compare.bind(null, GOLDEN_DIR, OUTPUT_DIR)
});
const defaultBrowserOptions = {
handleSIGINT: false,
executablePath: product === 'chromium' ? process.env.CHROME : process.env.FFOX,
dumpio: !!process.env.DUMPIO,
args: product === 'chromium' ? ['--no-sandbox'] : [],
};
const testOptions = {testRunner, expect, product, puppeteer, defaultBrowserOptions};
if (product === 'firefox' && defaultBrowserOptions.executablePath) {
beforeAll(async () => {
await require('../misc/install-preferences')(defaultBrowserOptions.executablePath);
console.log('RUNNING CUSTOM FIREFOX: ' + defaultBrowserOptions.executablePath);
});
}
require('./launcher.spec.js').addTests(testOptions);
require('./ignorehttpserrors.spec.js').addTests(testOptions);
describe('Browser', () => {
beforeAll(async state => {
state.browser = await puppeteer.launch(defaultBrowserOptions);
});
afterAll(async state => {
await state.browser.close();
state.browser = null;
});
require('./browser.spec.js').addTests(testOptions);
require('./browsercontext.spec.js').addTests(testOptions);
describe('Page', () => {
beforeEach(async state => {
state.context = await state.browser.createIncognitoBrowserContext();
state.page = await state.context.newPage();
});
afterEach(async state => {
await state.context.close();
state.context = null;
state.page = null;
});
require('./page.spec.js').addTests(testOptions);
require('./evaluation.spec.js').addTests(testOptions);
require('./navigation.spec.js').addTests(testOptions);
require('./dialog.spec.js').addTests(testOptions);
require('./frame.spec.js').addTests(testOptions);
require('./jshandle.spec.js').addTests(testOptions);
require('./elementhandle.spec.js').addTests(testOptions);
require('./target.spec.js').addTests(testOptions);
require('./waittask.spec.js').addTests(testOptions);
require('./queryselector.spec.js').addTests(testOptions);
require('./emulation.spec.js').addTests(testOptions);
require('./screenshot.spec.js').addTests(testOptions);
// Input tests
require('./keyboard.spec.js').addTests(testOptions);
require('./mouse.spec.js').addTests(testOptions);
require('./click.spec.js').addTests(testOptions);
require('./type.spec.js').addTests(testOptions);
require('./hover.spec.js').addTests(testOptions);
// Browser-specific page tests
if (product === 'firefox')
require('./firefoxonly.spec.js').addTests(testOptions);
else
require('./chromiumonly.spec.js').addTests(testOptions);
});
});
});

View File

@ -1,194 +0,0 @@
const utils = require('./utils');
module.exports.addTests = function({testRunner, expect, product}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
const FFOX = product === 'firefox';
const CHROME = product === 'chromium';
describe('Page.$', function() {
it('should query existing element', async({page, server}) => {
await page.setContent('<section>test</section>');
const element = await page.$('section');
expect(element).toBeTruthy();
});
it('should return null for non-existing element', async({page, server}) => {
const element = await page.$('non-existing-element');
expect(element).toBe(null);
});
});
describe('Page.$$', function() {
it('should query existing elements', async({page, server}) => {
await page.setContent('<div>A</div><br/><div>B</div>');
const elements = await page.$$('div');
expect(elements.length).toBe(2);
const promises = elements.map(element => page.evaluate(e => e.textContent, element));
expect(await Promise.all(promises)).toEqual(['A', 'B']);
});
it('should return empty array if nothing is found', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
const elements = await page.$$('div');
expect(elements.length).toBe(0);
});
});
describe('Page.$eval', function() {
it('should work', async({page, server}) => {
await page.setContent('<section id="testAttribute">43543</section>');
const idAttribute = await page.$eval('section', e => e.id);
expect(idAttribute).toBe('testAttribute');
});
it('should accept arguments', async({page, server}) => {
await page.setContent('<section>hello</section>');
const text = await page.$eval('section', (e, suffix) => e.textContent + suffix, ' world!');
expect(text).toBe('hello world!');
});
it('should accept ElementHandles as arguments', async({page, server}) => {
await page.setContent('<section>hello</section><div> world</div>');
const divHandle = await page.$('div');
const text = await page.$eval('section', (e, div) => e.textContent + div.textContent, divHandle);
expect(text).toBe('hello world');
});
it('should throw error if no element is found', async({page, server}) => {
let error = null;
await page.$eval('section', e => e.id).catch(e => error = e);
expect(error.message).toContain('failed to find element matching selector "section"');
});
});
describe('Page.$$eval', function() {
it('should work', async({page, server}) => {
await page.setContent('<div>hello</div><div>beautiful</div><div>world!</div>');
const divsCount = await page.$$eval('div', divs => divs.length);
expect(divsCount).toBe(3);
});
});
describe('Page.$x', function() {
it('should query existing element', async({page, server}) => {
await page.setContent('<section>test</section>');
const elements = await page.$x('/html/body/section');
expect(elements[0]).toBeTruthy();
expect(elements.length).toBe(1);
});
it('should return empty array for non-existing element', async({page, server}) => {
const element = await page.$x('/html/body/non-existing-element');
expect(element).toEqual([]);
});
it('should return multiple elements', async({page, sever}) => {
await page.setContent('<div></div><div></div>');
const elements = await page.$x('/html/body/div');
expect(elements.length).toBe(2);
});
});
describe('ElementHandle.$', function() {
it('should query existing element', async({page, server}) => {
await page.goto(server.PREFIX + '/playground.html');
await page.setContent('<html><body><div class="second"><div class="inner">A</div></div></body></html>');
const html = await page.$('html');
const second = await html.$('.second');
const inner = await second.$('.inner');
const content = await page.evaluate(e => e.textContent, inner);
expect(content).toBe('A');
});
it('should return null for non-existing element', async({page, server}) => {
await page.setContent('<html><body><div class="second"><div class="inner">B</div></div></body></html>');
const html = await page.$('html');
const second = await html.$('.third');
expect(second).toBe(null);
});
});
describe('ElementHandle.$$', function() {
it('should query existing elements', async({page, server}) => {
await page.setContent('<html><body><div>A</div><br/><div>B</div></body></html>');
const html = await page.$('html');
const elements = await html.$$('div');
expect(elements.length).toBe(2);
const promises = elements.map(element => page.evaluate(e => e.textContent, element));
expect(await Promise.all(promises)).toEqual(['A', 'B']);
});
it('should return empty array for non-existing elements', async({page, server}) => {
await page.setContent('<html><body><span>A</span><br/><span>B</span></body></html>');
const html = await page.$('html');
const elements = await html.$$('div');
expect(elements.length).toBe(0);
});
});
describe('ElementHandle.$eval', function() {
it('should work', async({page, server}) => {
await page.setContent('<html><body><div class="tweet"><div class="like">100</div><div class="retweets">10</div></div></body></html>');
const tweet = await page.$('.tweet');
const content = await tweet.$eval('.like', node => node.innerText);
expect(content).toBe('100');
});
it('should retrieve content from subtree', async({page, server}) => {
const htmlContent = '<div class="a">not-a-child-div</div><div id="myId"><div class="a">a-child-div</div></div>';
await page.setContent(htmlContent);
const elementHandle = await page.$('#myId');
const content = await elementHandle.$eval('.a', node => node.innerText);
expect(content).toBe('a-child-div');
});
it('should throw in case of missing selector', async({page, server}) => {
const htmlContent = '<div class="a">not-a-child-div</div><div id="myId"></div>';
await page.setContent(htmlContent);
const elementHandle = await page.$('#myId');
const errorMessage = await elementHandle.$eval('.a', node => node.innerText).catch(error => error.message);
expect(errorMessage).toBe(`Error: failed to find element matching selector ".a"`);
});
});
describe('ElementHandle.$$eval', function() {
it('should work', async({page, server}) => {
await page.setContent('<html><body><div class="tweet"><div class="like">100</div><div class="like">10</div></div></body></html>');
const tweet = await page.$('.tweet');
const content = await tweet.$$eval('.like', nodes => nodes.map(n => n.innerText));
expect(content).toEqual(['100', '10']);
});
it('should retrieve content from subtree', async({page, server}) => {
const htmlContent = '<div class="a">not-a-child-div</div><div id="myId"><div class="a">a1-child-div</div><div class="a">a2-child-div</div></div>';
await page.setContent(htmlContent);
const elementHandle = await page.$('#myId');
const content = await elementHandle.$$eval('.a', nodes => nodes.map(n => n.innerText));
expect(content).toEqual(['a1-child-div', 'a2-child-div']);
});
it('should not throw in case of missing selector', async({page, server}) => {
const htmlContent = '<div class="a">not-a-child-div</div><div id="myId"></div>';
await page.setContent(htmlContent);
const elementHandle = await page.$('#myId');
const nodesLength = await elementHandle.$$eval('.a', nodes => nodes.length);
expect(nodesLength).toBe(0);
});
});
describe('ElementHandle.$x', function() {
it('should query existing element', async({page, server}) => {
await page.goto(server.PREFIX + '/playground.html');
await page.setContent('<html><body><div class="second"><div class="inner">A</div></div></body></html>');
const html = await page.$('html');
const second = await html.$x(`./body/div[contains(@class, 'second')]`);
const inner = await second[0].$x(`./div[contains(@class, 'inner')]`);
const content = await page.evaluate(e => e.textContent, inner[0]);
expect(content).toBe('A');
});
it('should return null for non-existing element', async({page, server}) => {
await page.setContent('<html><body><div class="second"><div class="inner">B</div></div></body></html>');
const html = await page.$('html');
const second = await html.$x(`/div[contains(@class, 'third')]`);
expect(second).toEqual([]);
});
});
};

View File

@ -1,30 +0,0 @@
#!/usr/bin/env node
/**
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const path = require('path');
const {TestServer} = require('@pptr/testserver');
const port = 8907;
const httpsPort = 8908;
const assetsPath = path.join(__dirname, 'assets');
Promise.all([
TestServer.create(assetsPath, port),
TestServer.createHTTPS(assetsPath, httpsPort)
]).then(([server, httpsServer]) => {
console.log(`HTTP: server is running on http://localhost:${port}`);
console.log(`HTTPS: server is running on https://localhost:${httpsPort}`);
});

View File

@ -1,232 +0,0 @@
/**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
module.exports.addTests = function({testRunner, expect, product}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
const FFOX = product === 'firefox';
const CHROME = product === 'chromium';
describe('Page.screenshot', function() {
it('should work', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html');
const screenshot = await page.screenshot();
expect(screenshot).toBeGolden('screenshot-sanity.png');
});
it('should clip rect', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html');
const screenshot = await page.screenshot({
clip: {
x: 50,
y: 100,
width: 150,
height: 100
}
});
expect(screenshot).toBeGolden('screenshot-clip-rect.png');
});
it('should work for offscreen clip', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html');
const screenshot = await page.screenshot({
clip: {
x: 50,
y: 600,
width: 100,
height: 100
}
});
expect(screenshot).toBeGolden('screenshot-offscreen-clip.png');
});
it('should run in parallel', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html');
const promises = [];
for (let i = 0; i < 3; ++i) {
promises.push(page.screenshot({
clip: {
x: 50 * i,
y: 0,
width: 50,
height: 50
}
}));
}
const screenshots = await Promise.all(promises);
expect(screenshots[1]).toBeGolden('grid-cell-1.png');
});
it('should take fullPage screenshots', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html');
const screenshot = await page.screenshot({
fullPage: true
});
expect(screenshot).toBeGolden('screenshot-grid-fullpage.png');
});
it('should run in parallel in multiple pages', async({page, server, browser}) => {
const N = 2;
const pages = await Promise.all(Array(N).fill(0).map(async() => {
const page = await browser.newPage();
await page.goto(server.PREFIX + '/grid.html');
return page;
}));
const promises = [];
for (let i = 0; i < N; ++i)
promises.push(pages[i].screenshot({ clip: { x: 50 * i, y: 0, width: 50, height: 50 } }));
const screenshots = await Promise.all(promises);
for (let i = 0; i < N; ++i)
expect(screenshots[i]).toBeGolden(`grid-cell-${i}.png`);
await Promise.all(pages.map(page => page.close()));
});
(FFOX ? xit : it)('should allow transparency', async({page, server}) => {
await page.setViewport({ width: 100, height: 100 });
await page.goto(server.EMPTY_PAGE);
const screenshot = await page.screenshot({omitBackground: true});
expect(screenshot).toBeGolden('transparent.png');
});
(FFOX ? xit : it)('should render white background on jpeg file', async({page, server}) => {
await page.setViewport({ width: 100, height: 100 });
await page.goto(server.EMPTY_PAGE);
const screenshot = await page.screenshot({omitBackground: true, type: 'jpeg'});
expect(screenshot).toBeGolden('white.jpg');
});
it('should work with odd clip size on Retina displays', async({page, server}) => {
const screenshot = await page.screenshot({
clip: {
x: 0,
y: 0,
width: 11,
height: 11,
}
});
expect(screenshot).toBeGolden('screenshot-clip-odd-size.png');
});
it('should return base64', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html');
const screenshot = await page.screenshot({
encoding: 'base64'
});
expect(Buffer.isBuffer(screenshot)).toBe(false);
expect(Buffer.from(screenshot, 'base64')).toBeGolden('screenshot-sanity.png');
});
});
describe('ElementHandle.screenshot', function() {
it('should work', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.goto(server.PREFIX + '/grid.html');
await page.evaluate(() => window.scrollBy(50, 100));
const elementHandle = await page.$('.box:nth-of-type(3)');
const screenshot = await elementHandle.screenshot();
expect(screenshot).toBeGolden('screenshot-element-bounding-box.png');
});
it('should take into account padding and border', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.setContent(`
something above
<style>div {
border: 2px solid blue;
background: green;
width: 50px;
height: 50px;
}
</style>
<div></div>
`);
const elementHandle = await page.$('div');
const screenshot = await elementHandle.screenshot();
expect(screenshot).toBeGolden('screenshot-element-padding-border.png');
});
it('should capture full element when larger than viewport', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.setContent(`
something above
<style>
div.to-screenshot {
border: 1px solid blue;
width: 600px;
height: 600px;
margin-left: 50px;
}
::-webkit-scrollbar{
display: none;
}
</style>
<div class="to-screenshot"></div>
`);
const elementHandle = await page.$('div.to-screenshot');
const screenshot = await elementHandle.screenshot();
expect(screenshot).toBeGolden('screenshot-element-larger-than-viewport.png');
expect(await page.evaluate(() => ({ w: window.innerWidth, h: window.innerHeight }))).toEqual({ w: 500, h: 500 });
});
it('should scroll element into view', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.setContent(`
something above
<style>div.above {
border: 2px solid blue;
background: red;
height: 1500px;
}
div.to-screenshot {
border: 2px solid blue;
background: green;
width: 50px;
height: 50px;
}
</style>
<div class="above"></div>
<div class="to-screenshot"></div>
`);
const elementHandle = await page.$('div.to-screenshot');
const screenshot = await elementHandle.screenshot();
expect(screenshot).toBeGolden('screenshot-element-scrolled-into-view.png');
});
it('should work with a rotated element', async({page, server}) => {
await page.setViewport({width: 500, height: 500});
await page.setContent(`<div style="position:absolute;
top: 100px;
left: 100px;
width: 100px;
height: 100px;
background: green;
transform: rotateZ(200deg);">&nbsp;</div>`);
const elementHandle = await page.$('div');
const screenshot = await elementHandle.screenshot();
expect(screenshot).toBeGolden('screenshot-element-rotate.png');
});
it('should fail to screenshot a detached element', async({page, server}) => {
await page.setContent('<h1>remove this</h1>');
const elementHandle = await page.$('h1');
await page.evaluate(element => element.remove(), elementHandle);
const screenshotError = await elementHandle.screenshot().catch(error => error);
expect(screenshotError.message).toBe('Node is either not visible or not an HTMLElement');
});
(CHROME ? xit : it)('should not hang with zero width/height element', async({page, server}) => {
await page.setContent('<div style="width: 0; height: 0"></div>');
const div = await page.$('div');
await div.screenshot();
});
});
};

View File

@ -1,100 +0,0 @@
/**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const utils = require('./utils');
const {waitEvent} = utils;
const {TimeoutError} = require('../Errors');
module.exports.addTests = function({testRunner, expect, product}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
describe('Target', function() {
it('Browser.targets should return all of the targets', async({page, server, browser}) => {
// The pages will be the testing page and the original newtab page
const targets = browser.targets();
expect(targets.some(target => target.type() === 'page' &&
target.url() === 'about:blank')).toBeTruthy('Missing blank page');
});
it('Browser.pages should return all of the pages', async({page, server, browser}) => {
// The pages will be the testing page
const allPages = await browser.pages();
expect(allPages.length).toBe(2);
expect(allPages).toContain(page);
expect(allPages[0]).not.toBe(allPages[1]);
});
it('should be able to use the default page in the browser', async({page, server, browser}) => {
// The pages will be the testing page and the original newtab page
const allPages = await browser.pages();
const originalPage = allPages.find(p => p !== page);
expect(await originalPage.evaluate(() => ['Hello', 'world'].join(' '))).toBe('Hello world');
expect(await originalPage.$('body')).toBeTruthy();
});
it('should report when a new page is created and closed', async({page, server, browser}) => {
const [otherPage] = await Promise.all([
browser.waitForTarget(target => target.url() === server.EMPTY_PAGE2).then(target => target.page()),
page.evaluate(url => window.open(url), server.EMPTY_PAGE2),
]);
expect(await otherPage.evaluate(() => ['Hello', 'world'].join(' '))).toBe('Hello world');
expect(await otherPage.$('body')).toBeTruthy();
let allPages = await browser.pages();
expect(allPages).toContain(page);
expect(allPages).toContain(otherPage);
const closePagePromise = new Promise(fulfill => browser.once('targetdestroyed', target => fulfill(target.page())));
await otherPage.close();
expect(await closePagePromise).toBe(otherPage);
allPages = await Promise.all(browser.targets().map(target => target.page()));
expect(allPages).toContain(page);
expect(allPages).not.toContain(otherPage);
});
it('should report when a target url changes', async({page, server, browser}) => {
await page.goto(server.EMPTY_PAGE);
let changedTarget = new Promise(fulfill => browser.once('targetchanged', target => fulfill(target)));
await page.goto(server.EMPTY_PAGE2);
expect((await changedTarget).url()).toBe(server.EMPTY_PAGE2);
changedTarget = new Promise(fulfill => browser.once('targetchanged', target => fulfill(target)));
await page.goto(server.EMPTY_PAGE);
expect((await changedTarget).url()).toBe(server.EMPTY_PAGE);
});
});
describe('Browser.waitForTarget', () => {
it('should wait for a target', async function({browser, server}) {
let resolved = false;
const targetPromise = browser.waitForTarget(target => target.url() === server.EMPTY_PAGE);
targetPromise.then(() => resolved = true);
const page = await browser.newPage();
expect(resolved).toBe(false);
await page.goto(server.EMPTY_PAGE);
const target = await targetPromise;
expect(await target.page()).toBe(page);
await page.close();
});
it('should timeout waiting for a non-existent target', async function({browser, server}) {
let error = null;
await browser.waitForTarget(target => target.url() === server.EMPTY_PAGE, {
timeout: 1
}).catch(e => error = e);
expect(error).toBeInstanceOf(TimeoutError);
});
});
};

View File

@ -1,80 +0,0 @@
/**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const path = require('path');
const {TestServer} = require('@pptr/testserver');
const {TestRunner, Reporter} = require('@pptr/testrunner');
let parallel = 1;
const parallelArgIndex = process.argv.indexOf('-j');
if (parallelArgIndex !== -1)
parallel = parseInt(process.argv[parallelArgIndex + 1], 10);
require('events').defaultMaxListeners *= parallel;
let timeout = 10000;
if (!isNaN(process.env.TIMEOUT))
timeout = parseInt(process.env.TIMEOUT, 10);
const testRunner = new TestRunner({timeout, parallel});
console.log('Testing on Node', process.version);
testRunner.beforeAll(async state => {
const assetsPath = path.join(__dirname, 'assets');
const port = 8907 + state.parallelIndex * 2;
state.server = await TestServer.create(assetsPath, port);
state.server.PORT = port;
state.server.PREFIX = `http://localhost:${port}`;
state.server.EMPTY_PAGE = `http://localhost:${port}/empty.html`;
state.server.EMPTY_PAGE2 = `http://localhost:${port}/empty2.html`;
const httpsPort = port + 1;
state.httpsServer = await TestServer.createHTTPS(assetsPath, httpsPort);
state.httpsServer.PORT = httpsPort;
state.httpsServer.PREFIX = `https://localhost:${httpsPort}`;
state.httpsServer.EMPTY_PAGE = `https://localhost:${httpsPort}/empty.html`;
state.httpsServer.EMPTY_PAGE2 = `https://localhost:${httpsPort}/empty2.html`;
});
testRunner.afterAll(async({server, httpsServer}) => {
await Promise.all([
server.stop(),
httpsServer.stop(),
]);
});
testRunner.beforeEach(async({server, httpsServer}) => {
server.reset();
httpsServer.reset();
});
const product = process.env['PRODUCT'];
const pptrFirefox = require('..');
const pptrChromium = require('puppeteer');
if (product) {
console.log(`WARNING: Running with ${product} only product because of PRODUCT env`);
require('./puppeteer.spec.js').addTests({testRunner, product, puppeteer: product === 'chromium' ? pptrChromium : pptrFirefox});
} else {
require('./puppeteer.spec.js').addTests({testRunner, product: 'chromium', puppeteer: pptrChromium});
require('./puppeteer.spec.js').addTests({testRunner, product: 'firefox', puppeteer: pptrFirefox});
}
if (process.env.CI && testRunner.hasFocusedTestsOrSuites()) {
console.error('ERROR: "focused" tests/suites are prohibitted on bots. Remove any "fit"/"fdescribe" declarations.');
process.exit(1);
}
new Reporter(testRunner, path.join(__dirname, '..'));
testRunner.run();

View File

@ -1,84 +0,0 @@
/**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
module.exports.addTests = function({testRunner, expect, product}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
const FFOX = product === 'firefox';
const CHROME = product === 'chromium';
describe('Page.type', () => {
it('should type into the textarea', async({page, server}) => {
await page.goto(server.PREFIX + '/input/textarea.html');
const textarea = await page.$('textarea');
await textarea.type('Type in this text!');
expect(await page.evaluate(() => result)).toBe('Type in this text!');
});
it('should move with the arrow keys', async({page, server}) => {
await page.goto(server.PREFIX + '/input/textarea.html');
await page.type('textarea', 'Hello World!');
expect(await page.evaluate(() => document.querySelector('textarea').value)).toBe('Hello World!');
for (let i = 0; i < 'World!'.length; i++)
page.keyboard.press('ArrowLeft');
await page.keyboard.type('inserted ');
expect(await page.evaluate(() => document.querySelector('textarea').value)).toBe('Hello inserted World!');
page.keyboard.down('Shift');
for (let i = 0; i < 'inserted '.length; i++)
page.keyboard.press('ArrowLeft');
page.keyboard.up('Shift');
await page.keyboard.press('Backspace');
expect(await page.evaluate(() => document.querySelector('textarea').value)).toBe('Hello World!');
});
});
describe('ElementHandle.press', () => {
it('should send a character with ElementHandle.press', async({page, server}) => {
await page.goto(server.PREFIX + '/input/textarea.html');
const textarea = await page.$('textarea');
await textarea.press('a');
expect(await page.evaluate(() => document.querySelector('textarea').value)).toBe('a');
await page.evaluate(() => window.addEventListener('keydown', e => e.preventDefault(), true));
await textarea.press('a');
expect(await page.evaluate(() => document.querySelector('textarea').value)).toBe('a');
});
it('should specify location', async({page, server}) => {
await page.goto(server.PREFIX + '/input/textarea.html');
await page.evaluate(() => {
window.addEventListener('keydown', event => window.keyLocation = event.location, true);
});
const textarea = await page.$('textarea');
await textarea.press('Digit5');
expect(await page.evaluate('keyLocation')).toBe(0);
await textarea.press('ControlLeft');
expect(await page.evaluate('keyLocation')).toBe(1);
await textarea.press('ControlRight');
expect(await page.evaluate('keyLocation')).toBe(2);
await textarea.press('NumpadSubtract');
expect(await page.evaluate('keyLocation')).toBe(3);
});
});
};

View File

@ -1,98 +0,0 @@
/**
* Copyright 2017 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const fs = require('fs');
const path = require('path');
const utils = module.exports = {
/**
* @param {!Page} page
* @param {string} frameId
* @param {string} url
* @return {!Puppeteer.Frame}
*/
attachFrame: async function(page, frameId, url) {
await page.evaluate(attachFrame, frameId, url);
async function attachFrame(frameId, url) {
const frame = document.createElement('iframe');
frame.src = url;
frame.id = frameId;
document.body.appendChild(frame);
await new Promise(x => frame.onload = x);
}
},
/**
* @param {!Page} page
* @param {string} frameId
*/
detachFrame: async function(page, frameId) {
await page.evaluate(detachFrame, frameId);
function detachFrame(frameId) {
const frame = document.getElementById(frameId);
frame.remove();
}
},
/**
* @param {!Page} page
* @param {string} frameId
* @param {string} url
*/
navigateFrame: async function(page, frameId, url) {
await page.evaluate(navigateFrame, frameId, url);
function navigateFrame(frameId, url) {
const frame = document.getElementById(frameId);
frame.src = url;
return new Promise(x => frame.onload = x);
}
},
/**
* @param {!Frame} frame
* @param {string=} indentation
* @return {!Array<string>}
*/
dumpFrames: function(frame, indentation) {
indentation = indentation || '';
let description = frame.url().replace(/:\d{4}\//, ':<PORT>/');
if (frame.name())
description += ' (' + frame.name() + ')';
let result = [indentation + description];
for (const child of frame.childFrames())
result.push(...utils.dumpFrames(child, ' ' + indentation));
return result;
},
/**
* @param {!EventEmitter} emitter
* @param {string} eventName
* @return {!Promise<!Object>}
*/
waitEvent: function(emitter, eventName, predicate = () => true) {
return new Promise(fulfill => {
emitter.on(eventName, function listener(event) {
if (!predicate(event))
return;
emitter.removeListener(eventName, listener);
fulfill(event);
});
});
},
};

View File

@ -1,423 +0,0 @@
/**
* Copyright 2018 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const utils = require('./utils');
const {TimeoutError} = require('../Errors');
module.exports.addTests = function({testRunner, expect, product}) {
const {describe, xdescribe, fdescribe} = testRunner;
const {it, fit, xit} = testRunner;
const {beforeAll, beforeEach, afterAll, afterEach} = testRunner;
const FFOX = product === 'firefox';
const CHROME = product === 'chromium';
describe('Page.waitForFunction', function() {
it('should accept a string', async({page, server}) => {
const watchdog = page.waitForFunction('window.__FOO === 1');
await page.evaluate(() => window.__FOO = 1);
await watchdog;
});
it('should work when resolved right before execution context disposal', async({page, server}) => {
await page.evaluateOnNewDocument(() => window.__RELOADED = true);
await page.waitForFunction(() => {
if (!window.__RELOADED)
window.location.reload();
return true;
});
});
it('should poll on interval', async({page, server}) => {
let success = false;
const startTime = Date.now();
const polling = 100;
const watchdog = page.waitForFunction(() => window.__FOO === 'hit', {polling})
.then(() => success = true);
await page.evaluate(() => window.__FOO = 'hit');
expect(success).toBe(false);
await page.evaluate(() => document.body.appendChild(document.createElement('div')));
await watchdog;
expect(Date.now() - startTime).not.toBeLessThan(polling / 2);
});
it('should poll on mutation', async({page, server}) => {
let success = false;
const watchdog = page.waitForFunction(() => window.__FOO === 'hit', {polling: 'mutation'})
.then(() => success = true);
await page.evaluate(() => window.__FOO = 'hit');
expect(success).toBe(false);
await page.evaluate(() => document.body.appendChild(document.createElement('div')));
await watchdog;
});
it('should poll on raf', async({page, server}) => {
const watchdog = page.waitForFunction(() => window.__FOO === 'hit', {polling: 'raf'});
await page.evaluate(() => window.__FOO = 'hit');
await watchdog;
});
xit('should work with strict CSP policy', async({page, server}) => {
server.setCSP('/empty.html', 'script-src ' + server.PREFIX);
await page.goto(server.EMPTY_PAGE);
const watchdog = page.waitForFunction(() => window.__FOO === 'hit', {polling: 'raf'});
await page.evaluate(() => window.__FOO = 'hit');
await watchdog;
});
it('should throw on bad polling value', async({page, server}) => {
let error = null;
try {
await page.waitForFunction(() => !!document.body, {polling: 'unknown'});
} catch (e) {
error = e;
}
expect(error).toBeTruthy();
expect(error.message).toContain('polling');
});
it('should throw negative polling interval', async({page, server}) => {
let error = null;
try {
await page.waitForFunction(() => !!document.body, {polling: -10});
} catch (e) {
error = e;
}
expect(error).toBeTruthy();
expect(error.message).toContain('Cannot poll with non-positive interval');
});
it('should return the success value as a JSHandle', async({page}) => {
expect(await (await page.waitForFunction(() => 5)).jsonValue()).toBe(5);
});
it('should return the window as a success value', async({ page }) => {
expect(await page.waitForFunction(() => window)).toBeTruthy();
});
it('should accept ElementHandle arguments', async({page}) => {
await page.setContent('<div></div>');
const div = await page.$('div');
let resolved = false;
const waitForFunction = page.waitForFunction(element => !element.parentElement, {}, div).then(() => resolved = true);
expect(resolved).toBe(false);
await page.evaluate(element => element.remove(), div);
await waitForFunction;
});
it('should respect timeout', async({page}) => {
let error = null;
await page.waitForFunction('false', {timeout: 10}).catch(e => error = e);
expect(error).toBeTruthy();
expect(error.message).toContain('waiting for function failed: timeout');
expect(error).toBeInstanceOf(TimeoutError);
});
it('should disable timeout when its set to 0', async({page}) => {
const watchdog = page.waitForFunction(() => {
window.__counter = (window.__counter || 0) + 1;
return window.__injected;
}, {timeout: 0, polling: 10});
await page.waitForFunction(() => window.__counter > 10);
await page.evaluate(() => window.__injected = true);
await watchdog;
});
it('should survive navigations', async({page, server}) => {
const watchdog = page.waitForFunction(() => window.__done);
await page.goto(server.EMPTY_PAGE);
await page.goto(server.PREFIX + '/consolelog.html');
await page.evaluate(() => window.__done = true);
await watchdog;
});
});
describe('Page.waitForSelector', function() {
const addElement = tag => document.body.appendChild(document.createElement(tag));
it('should immediately resolve promise if node exists', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
const frame = page.mainFrame();
await frame.waitForSelector('*');
await frame.evaluate(addElement, 'div');
await frame.waitForSelector('div');
});
it('should resolve promise when node is added', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
const frame = page.mainFrame();
const watchdog = frame.waitForSelector('div');
await frame.evaluate(addElement, 'br');
await frame.evaluate(addElement, 'div');
const eHandle = await watchdog;
const tagName = await eHandle.getProperty('tagName').then(e => e.jsonValue());
expect(tagName).toBe('DIV');
});
it('should work when node is added through innerHTML', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
const watchdog = page.waitForSelector('h3 div');
await page.evaluate(addElement, 'span');
await page.evaluate(() => document.querySelector('span').innerHTML = '<h3><div></div></h3>');
await watchdog;
});
it('Page.waitForSelector is shortcut for main frame', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE2);
const otherFrame = page.frames()[1];
const watchdog = page.waitForSelector('div');
await otherFrame.evaluate(addElement, 'div');
await page.evaluate(addElement, 'div');
const eHandle = await watchdog;
expect(await page.mainFrame().evaluate(e => !!e, eHandle)).toBe(true);
});
it('should run in specified frame', async({page, server}) => {
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
await utils.attachFrame(page, 'frame2', server.EMPTY_PAGE);
const frame1 = page.frames()[1];
const frame2 = page.frames()[2];
const waitForSelectorPromise = frame2.waitForSelector('div');
await frame1.evaluate(addElement, 'div');
await frame2.evaluate(addElement, 'div');
const eHandle = await waitForSelectorPromise;
expect(await frame2.evaluate(e => !!e, eHandle)).toBe(true);
});
it('should throw if evaluation failed', async({page, server}) => {
await page.evaluateOnNewDocument(function() {
document.querySelector = null;
});
await page.goto(server.EMPTY_PAGE);
let error = null;
await page.waitForSelector('*').catch(e => error = e);
expect(error.message).toContain('document.querySelector is not a function');
});
it('should throw when frame is detached', async({page, server}) => {
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
const frame = page.frames()[1];
let waitError = null;
const waitPromise = frame.waitForSelector('.box').catch(e => waitError = e);
await utils.detachFrame(page, 'frame1');
await waitPromise;
expect(waitError).toBeTruthy();
expect(waitError.message).toContain('waitForFunction failed: frame got detached.');
});
xit('should survive cross-process navigation', async({page, server}) => {
let boxFound = false;
const waitForSelector = page.waitForSelector('.box').then(() => boxFound = true);
await page.goto(server.EMPTY_PAGE);
expect(boxFound).toBe(false);
await page.reload();
expect(boxFound).toBe(false);
await page.goto(server.CROSS_PROCESS_PREFIX + '/grid.html');
await waitForSelector;
expect(boxFound).toBe(true);
});
it('should wait for visible', async({page, server}) => {
let divFound = false;
const waitForSelector = page.waitForSelector('div', {visible: true}).then(() => divFound = true);
await page.setContent(`<div style='display: none; visibility: hidden;'>1</div>`);
expect(divFound).toBe(false);
await page.evaluate(() => document.querySelector('div').style.removeProperty('display'));
expect(divFound).toBe(false);
await page.evaluate(() => document.querySelector('div').style.removeProperty('visibility'));
expect(await waitForSelector).toBe(true);
expect(divFound).toBe(true);
});
it('should wait for visible recursively', async({page, server}) => {
let divVisible = false;
const waitForSelector = page.waitForSelector('div#inner', {visible: true}).then(() => divVisible = true);
await page.setContent(`<div style='display: none; visibility: hidden;'><div id="inner">hi</div></div>`);
expect(divVisible).toBe(false);
await page.evaluate(() => document.querySelector('div').style.removeProperty('display'));
expect(divVisible).toBe(false);
await page.evaluate(() => document.querySelector('div').style.removeProperty('visibility'));
expect(await waitForSelector).toBe(true);
expect(divVisible).toBe(true);
});
it('hidden should wait for visibility: hidden', async({page, server}) => {
let divHidden = false;
await page.setContent(`<div style='display: block;'></div>`);
const waitForSelector = page.waitForSelector('div', {hidden: true}).then(() => divHidden = true);
await page.waitForSelector('div'); // do a round trip
expect(divHidden).toBe(false);
await page.evaluate(() => document.querySelector('div').style.setProperty('visibility', 'hidden'));
expect(await waitForSelector).toBe(true);
expect(divHidden).toBe(true);
});
it('hidden should wait for display: none', async({page, server}) => {
let divHidden = false;
await page.setContent(`<div style='display: block;'></div>`);
const waitForSelector = page.waitForSelector('div', {hidden: true}).then(() => divHidden = true);
await page.waitForSelector('div'); // do a round trip
expect(divHidden).toBe(false);
await page.evaluate(() => document.querySelector('div').style.setProperty('display', 'none'));
expect(await waitForSelector).toBe(true);
expect(divHidden).toBe(true);
});
it('hidden should wait for removal', async({page, server}) => {
await page.setContent(`<div></div>`);
let divRemoved = false;
const waitForSelector = page.waitForSelector('div', {hidden: true}).then(() => divRemoved = true);
await page.waitForSelector('div'); // do a round trip
expect(divRemoved).toBe(false);
await page.evaluate(() => document.querySelector('div').remove());
expect(await waitForSelector).toBe(true);
expect(divRemoved).toBe(true);
});
it('should respect timeout', async({page, server}) => {
let error = null;
await page.waitForSelector('div', {timeout: 10}).catch(e => error = e);
expect(error).toBeTruthy();
expect(error.message).toContain('waiting for selector "div" failed: timeout');
expect(error).toBeInstanceOf(TimeoutError);
});
it('should have an error message specifically for awaiting an element to be hidden', async({page, server}) => {
await page.setContent(`<div></div>`);
let error = null;
await page.waitForSelector('div', {hidden: true, timeout: 10}).catch(e => error = e);
expect(error).toBeTruthy();
expect(error.message).toContain('waiting for selector "div" to be hidden failed: timeout');
});
it('should respond to node attribute mutation', async({page, server}) => {
let divFound = false;
const waitForSelector = page.waitForSelector('.zombo').then(() => divFound = true);
await page.setContent(`<div class='notZombo'></div>`);
expect(divFound).toBe(false);
await page.evaluate(() => document.querySelector('div').className = 'zombo');
expect(await waitForSelector).toBe(true);
});
it('should return the element handle', async({page, server}) => {
const waitForSelector = page.waitForSelector('.zombo');
await page.setContent(`<div class='zombo'>anything</div>`);
expect(await page.evaluate(x => x.textContent, await waitForSelector)).toBe('anything');
});
it('should have correct stack trace for timeout', async({page, server}) => {
let error;
await page.waitForSelector('.zombo', {timeout: 10}).catch(e => error = e);
expect(error.stack).toContain('waittask.spec.js');
});
});
describe('Frame.waitForXPath', function() {
const addElement = tag => document.body.appendChild(document.createElement(tag));
it('should support some fancy xpath', async({page, server}) => {
await page.setContent(`<p>red herring</p><p>hello world </p>`);
const waitForXPath = page.waitForXPath('//p[normalize-space(.)="hello world"]');
expect(await page.evaluate(x => x.textContent, await waitForXPath)).toBe('hello world ');
});
it('should respect timeout', async({page}) => {
let error = null;
await page.waitForXPath('//div', {timeout: 10}).catch(e => error = e);
expect(error).toBeTruthy();
expect(error.message).toContain('waiting for XPath "//div" failed: timeout');
expect(error).toBeInstanceOf(TimeoutError);
});
it('should run in specified frame', async({page, server}) => {
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
await utils.attachFrame(page, 'frame2', server.EMPTY_PAGE);
const frame1 = page.frames()[1];
const frame2 = page.frames()[2];
const waitForXPathPromise = frame2.waitForXPath('//div');
await frame1.evaluate(addElement, 'div');
await frame2.evaluate(addElement, 'div');
const eHandle = await waitForXPathPromise;
expect(await frame2.evaluate(e => !!e, eHandle)).toBe(true);
});
it('should throw if evaluation failed', async({page, server}) => {
await page.evaluateOnNewDocument(function() {
document.evaluate = null;
});
await page.goto(server.EMPTY_PAGE);
let error = null;
await page.waitForXPath('*').catch(e => error = e);
expect(error.message).toContain('document.evaluate is not a function');
});
it('should throw when frame is detached', async({page, server}) => {
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
const frame = page.frames()[1];
let waitError = null;
const waitPromise = frame.waitForXPath('//*[@class="box"]').catch(e => waitError = e);
await utils.detachFrame(page, 'frame1');
await waitPromise;
expect(waitError).toBeTruthy();
expect(waitError.message).toContain('waitForFunction failed: frame got detached.');
});
it('hidden should wait for display: none', async({page, server}) => {
let divHidden = false;
await page.setContent(`<div style='display: block;'></div>`);
const waitForXPath = page.waitForXPath('//div', {hidden: true}).then(() => divHidden = true);
await page.waitForXPath('//div'); // do a round trip
expect(divHidden).toBe(false);
await page.evaluate(() => document.querySelector('div').style.setProperty('display', 'none'));
expect(await waitForXPath).toBe(true);
expect(divHidden).toBe(true);
});
it('should return the element handle', async({page, server}) => {
const waitForXPath = page.waitForXPath('//*[@class="zombo"]');
await page.setContent(`<div class='zombo'>anything</div>`);
expect(await page.evaluate(x => x.textContent, await waitForXPath)).toBe('anything');
});
it('should allow you to select a text node', async({page, server}) => {
await page.setContent(`<div>some text</div>`);
const text = await page.waitForXPath('//div/text()');
expect(await (await text.getProperty('nodeType')).jsonValue()).toBe(3 /* Node.TEXT_NODE */);
});
it('should allow you to select an element with single slash', async({page, server}) => {
await page.setContent(`<div>some text</div>`);
const waitForXPath = page.waitForXPath('/html/body/div');
expect(await page.evaluate(x => x.textContent, await waitForXPath)).toBe('some text');
});
});
describe('Page.waitFor', function() {
it('should wait for selector', async({page, server}) => {
let found = false;
const waitFor = page.waitFor('div').then(() => found = true);
await page.goto(server.EMPTY_PAGE);
expect(found).toBe(false);
await page.goto(server.PREFIX + '/grid.html');
await waitFor;
expect(found).toBe(true);
});
it('should wait for an xpath', async({page, server}) => {
let found = false;
const waitFor = page.waitFor('//div').then(() => found = true);
await page.goto(server.EMPTY_PAGE);
expect(found).toBe(false);
await page.goto(server.PREFIX + '/grid.html');
await waitFor;
expect(found).toBe(true);
});
it('should not allow you to select an element with single slash xpath', async({page, server}) => {
await page.setContent(`<div>some text</div>`);
let error = null;
await page.waitFor('/html/body/div').catch(e => error = e);
expect(error).toBeTruthy();
});
it('should timeout', async({page, server}) => {
const startTime = Date.now();
const timeout = 42;
await page.waitFor(timeout);
expect(Date.now() - startTime).not.toBeLessThan(timeout / 2);
});
it('should wait for predicate', async({page, server}) => {
await page.goto(server.EMPTY_PAGE);
await Promise.all([
page.waitFor(() => window.location.href.includes('woof')),
page.goto(server.EMPTY_PAGE + '#woof'),
]);
});
it('should throw when unknown type', async({page, server}) => {
let error = null;
await page.waitFor({foo: 'bar'}).catch(e => error = e);
expect(error.message).toContain('Unsupported target type');
});
it('should wait for predicate with arguments', async({page, server}) => {
await page.waitFor((arg1, arg2) => arg1 !== arg2, {}, 1, 2);
});
});
};

Some files were not shown because too many files have changed in this diff Show More