refactor: tests use toHaveLength and waitEvent (#10061)

This commit is contained in:
Nikolay Vitkov 2023-04-25 15:02:25 +02:00 committed by GitHub
parent 8124a7d5bf
commit 5e79d53bd3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
33 changed files with 400 additions and 504 deletions

View File

@ -61,7 +61,7 @@ describe('Target.createCDPSession', function () {
const client = await page.target().createCDPSession();
await client.send('Network.enable');
const events = [];
const events: unknown[] = [];
client.on('Network.requestWillBeSent', event => {
return events.push(event);
});
@ -69,7 +69,7 @@ describe('Target.createCDPSession', function () {
waitEvent(client, 'Network.requestWillBeSent'),
page.goto(server.EMPTY_PAGE),
]);
expect(events.length).toBe(1);
expect(events).toHaveLength(1);
});
it('should enable and disable domains independently', async () => {
const {page} = getTestState();

View File

@ -40,7 +40,7 @@ describe('EventEmitter', () => {
emitter[methodName]('foo', listener);
emitter.emit('foo', data);
expect(listener.callCount).toEqual(1);
expect(listener.firstCall.args[0]!).toBe(data);
expect(listener.firstCall.args[0]).toBe(data);
});
it(`${methodName}: supports chaining`, () => {
@ -116,7 +116,7 @@ describe('EventEmitter', () => {
emitter.emit('foo', data);
expect(listener.callCount).toEqual(1);
expect(listener.firstCall.args[0]!).toBe(data);
expect(listener.firstCall.args[0]).toBe(data);
});
it('returns true if the event has listeners', () => {

View File

@ -551,7 +551,7 @@ describe('NetworkManager', () => {
networkId: '11ACE9783588040D644B905E8B55285B',
});
expect(requests.length).toBe(2);
expect(requests).toHaveLength(2);
});
it(`should handle Network.responseReceivedExtraInfo event after Network.responseReceived event (github.com/puppeteer/puppeteer/issues/8234)`, async () => {
const mockCDPSession = new MockCDPSession();
@ -668,7 +668,7 @@ describe('NetworkManager', () => {
shouldReportCorbBlocking: false,
});
expect(requests.length).toBe(1);
expect(requests).toHaveLength(1);
});
it(`should resolve the response once the late responseReceivedExtraInfo event arrives`, async () => {
@ -796,8 +796,8 @@ describe('NetworkManager', () => {
shouldReportCorbBlocking: false,
});
expect(pendingRequests.length).toBe(1);
expect(finishedRequests.length).toBe(0);
expect(pendingRequests).toHaveLength(1);
expect(finishedRequests).toHaveLength(0);
expect(pendingRequests[0]!.response()).toEqual(null);
// The extra info might arrive late.
@ -818,8 +818,8 @@ describe('NetworkManager', () => {
'HTTP/1.1 200 OK\\r\\nCache-Control: no-cache, no-store\\r\\nContent-Type: text/html; charset=utf-8\\r\\nDate: Wed, 10 Aug 2022 09:04:39 GMT\\r\\nConnection: keep-alive\\r\\nKeep-Alive: timeout=5\\r\\nContent-Length: 0\\r\\n\\r\\n',
});
expect(pendingRequests.length).toBe(1);
expect(finishedRequests.length).toBe(1);
expect(pendingRequests).toHaveLength(1);
expect(finishedRequests).toHaveLength(1);
expect(pendingRequests[0]!.response()).not.toEqual(null);
});
@ -981,8 +981,8 @@ describe('NetworkManager', () => {
frameId: '07D18B8630A8161C72B6079B74123D60',
});
expect(requests.length).toBe(1);
expect(responses.length).toBe(1);
expect(requests).toHaveLength(1);
expect(responses).toHaveLength(1);
expect(requests[0]!.response()).not.toEqual(null);
});
@ -1127,8 +1127,8 @@ describe('NetworkManager', () => {
'HTTP/1.1 200 OK\r\nCache-Control: no-cache, no-store\r\nContent-Type: text/html; charset=utf-8\r\nDate: Wed, 10 Aug 2022 11:21:22 GMT\r\nConnection: keep-alive\r\nKeep-Alive: timeout=5\r\nContent-Length: 0\r\n\r\n',
});
expect(requests.length).toBe(1);
expect(responses.length).toBe(1);
expect(requests).toHaveLength(1);
expect(responses).toHaveLength(1);
expect(requests[0]!.response()).not.toEqual(null);
});

View File

@ -21,7 +21,7 @@ import {
} from 'puppeteer-core/internal/common/Browser.js';
import {getTestState} from './mocha-utils'; // eslint-disable-line import/extensions
import utils from './utils.js';
import {attachFrame} from './utils.js';
describe('TargetManager', () => {
/* We use a special browser for this test as we need the --site-per-process flag */
@ -74,7 +74,7 @@ describe('TargetManager', () => {
let framePromise = page.waitForFrame(frame => {
return frame.url().endsWith('/empty.html');
});
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
await attachFrame(page, 'frame1', server.EMPTY_PAGE);
await framePromise;
expect(await context.pages()).toHaveLength(1);
expect(targetManager.getAvailableTargets().size).toBe(3);
@ -84,7 +84,7 @@ describe('TargetManager', () => {
framePromise = page.waitForFrame(frame => {
return frame.url() === server.CROSS_PROCESS_PREFIX + '/empty.html';
});
await utils.attachFrame(
await attachFrame(
page,
'frame2',
server.CROSS_PROCESS_PREFIX + '/empty.html'
@ -97,7 +97,7 @@ describe('TargetManager', () => {
framePromise = page.waitForFrame(frame => {
return frame.url() === server.CROSS_PROCESS_PREFIX + '/empty.html';
});
await utils.attachFrame(
await attachFrame(
page,
'frame3',
server.CROSS_PROCESS_PREFIX + '/empty.html'

View File

@ -220,7 +220,7 @@ describe('Accessibility', function () {
// See https://chromium-review.googlesource.com/c/chromium/src/+/3088862
assert(snapshot);
assert(snapshot.children);
assert(snapshot.children[0]!);
assert(snapshot.children[0]);
expect(snapshot.children[0]!.roledescription).toBeUndefined();
});
it('orientation', async () => {
@ -232,7 +232,7 @@ describe('Accessibility', function () {
const snapshot = await page.accessibility.snapshot();
assert(snapshot);
assert(snapshot.children);
assert(snapshot.children[0]!);
assert(snapshot.children[0]);
expect(snapshot.children[0]!.orientation).toEqual('vertical');
});
it('autocomplete', async () => {
@ -242,7 +242,7 @@ describe('Accessibility', function () {
const snapshot = await page.accessibility.snapshot();
assert(snapshot);
assert(snapshot.children);
assert(snapshot.children[0]!);
assert(snapshot.children[0]);
expect(snapshot.children[0]!.autocomplete).toEqual('list');
});
it('multiselectable', async () => {
@ -254,7 +254,7 @@ describe('Accessibility', function () {
const snapshot = await page.accessibility.snapshot();
assert(snapshot);
assert(snapshot.children);
assert(snapshot.children[0]!);
assert(snapshot.children[0]);
expect(snapshot.children[0]!.multiselectable).toEqual(true);
});
it('keyshortcuts', async () => {
@ -266,7 +266,7 @@ describe('Accessibility', function () {
const snapshot = await page.accessibility.snapshot();
assert(snapshot);
assert(snapshot.children);
assert(snapshot.children[0]!);
assert(snapshot.children[0]);
expect(snapshot.children[0]!.keyshortcuts).toEqual('foo');
});
describe('filtering children of leaf nodes', function () {
@ -351,7 +351,7 @@ describe('Accessibility', function () {
const snapshot = await page.accessibility.snapshot();
assert(snapshot);
assert(snapshot.children);
expect(snapshot.children[0]!).toEqual(golden);
expect(snapshot.children[0]).toEqual(golden);
});
it('rich text editable fields with role should have children', async () => {
const {page, isFirefox} = getTestState();
@ -388,7 +388,7 @@ describe('Accessibility', function () {
const snapshot = await page.accessibility.snapshot();
assert(snapshot);
assert(snapshot.children);
expect(snapshot.children[0]!).toEqual(golden);
expect(snapshot.children[0]).toEqual(golden);
});
// Firefox does not support contenteditable="plaintext-only".
@ -401,7 +401,7 @@ describe('Accessibility', function () {
const snapshot = await page.accessibility.snapshot();
assert(snapshot);
assert(snapshot.children);
expect(snapshot.children[0]!).toEqual({
expect(snapshot.children[0]).toEqual({
role: 'textbox',
name: '',
value: 'Edit this image:',
@ -431,7 +431,7 @@ describe('Accessibility', function () {
const snapshot = await page.accessibility.snapshot();
assert(snapshot);
assert(snapshot.children);
expect(snapshot.children[0]!).toEqual(golden);
expect(snapshot.children[0]).toEqual(golden);
});
it('checkbox with and tabIndex and label should not have children', async () => {
const {page, isFirefox} = getTestState();
@ -455,7 +455,7 @@ describe('Accessibility', function () {
const snapshot = await page.accessibility.snapshot();
assert(snapshot);
assert(snapshot.children);
expect(snapshot.children[0]!).toEqual(golden);
expect(snapshot.children[0]).toEqual(golden);
});
it('checkbox without label should not have children', async () => {
const {page, isFirefox} = getTestState();
@ -479,7 +479,7 @@ describe('Accessibility', function () {
const snapshot = await page.accessibility.snapshot();
assert(snapshot);
assert(snapshot.children);
expect(snapshot.children[0]!).toEqual(golden);
expect(snapshot.children[0]).toEqual(golden);
});
describe('root option', function () {

View File

@ -25,7 +25,7 @@ import {
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
import utils from './utils.js';
import {attachFrame, detachFrame} from './utils.js';
describe('AriaQueryHandler', () => {
setupTestBrowserHooks();
@ -331,7 +331,7 @@ describe('AriaQueryHandler', () => {
const {page, server} = getTestState();
await page.goto(server.EMPTY_PAGE);
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
await attachFrame(page, 'frame1', server.EMPTY_PAGE);
const otherFrame = page.frames()[1];
const watchdog = page.waitForSelector('aria/[role="button"]');
await otherFrame!.evaluate(addElement, 'button');
@ -343,8 +343,8 @@ describe('AriaQueryHandler', () => {
it('should run in specified frame', async () => {
const {page, server} = getTestState();
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
await utils.attachFrame(page, 'frame2', server.EMPTY_PAGE);
await attachFrame(page, 'frame1', server.EMPTY_PAGE);
await attachFrame(page, 'frame2', server.EMPTY_PAGE);
const frame1 = page.frames()[1];
const frame2 = page.frames()[2];
const waitForSelectorPromise = frame2!.waitForSelector(
@ -359,7 +359,7 @@ describe('AriaQueryHandler', () => {
it('should throw when frame is detached', async () => {
const {page, server} = getTestState();
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
await attachFrame(page, 'frame1', server.EMPTY_PAGE);
const frame = page.frames()[1];
let waitError!: Error;
const waitPromise = frame!
@ -367,7 +367,7 @@ describe('AriaQueryHandler', () => {
.catch(error => {
return (waitError = error);
});
await utils.detachFrame(page, 'frame1');
await detachFrame(page, 'frame1');
await waitPromise;
expect(waitError).toBeTruthy();
expect(waitError.message).toContain(

View File

@ -24,7 +24,7 @@ describe('BrowserContext', function () {
setupTestBrowserHooks();
it('should have default context', async () => {
const {browser} = getTestState();
expect(browser.browserContexts().length).toEqual(1);
expect(browser.browserContexts()).toHaveLength(1);
const defaultContext = browser.browserContexts()[0]!;
expect(defaultContext!.isIncognito()).toBe(false);
let error!: Error;
@ -37,26 +37,26 @@ describe('BrowserContext', function () {
it('should create new incognito context', async () => {
const {browser} = getTestState();
expect(browser.browserContexts().length).toBe(1);
expect(browser.browserContexts()).toHaveLength(1);
const context = await browser.createIncognitoBrowserContext();
expect(context.isIncognito()).toBe(true);
expect(browser.browserContexts().length).toBe(2);
expect(browser.browserContexts()).toHaveLength(2);
expect(browser.browserContexts().indexOf(context) !== -1).toBe(true);
await context.close();
expect(browser.browserContexts().length).toBe(1);
expect(browser.browserContexts()).toHaveLength(1);
});
it('should close all belonging targets once closing context', async () => {
const {browser} = getTestState();
expect((await browser.pages()).length).toBe(1);
expect(await browser.pages()).toHaveLength(1);
const context = await browser.createIncognitoBrowserContext();
await context.newPage();
expect((await browser.pages()).length).toBe(2);
expect((await context.pages()).length).toBe(1);
expect(await browser.pages()).toHaveLength(2);
expect(await context.pages()).toHaveLength(1);
await context.close();
expect((await browser.pages()).length).toBe(1);
expect(await browser.pages()).toHaveLength(1);
});
it('window.open should use parent tab context', async () => {
const {browser, server} = getTestState();
@ -160,8 +160,8 @@ describe('BrowserContext', function () {
// 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);
expect(context1.targets()).toHaveLength(0);
expect(context2.targets()).toHaveLength(0);
// Create a page in first incognito context.
const page1 = await context1.newPage();
@ -171,8 +171,8 @@ describe('BrowserContext', function () {
document.cookie = 'name=page1';
});
expect(context1.targets().length).toBe(1);
expect(context2.targets().length).toBe(0);
expect(context1.targets()).toHaveLength(1);
expect(context2.targets()).toHaveLength(0);
// Create a page in second incognito context.
const page2 = await context2.newPage();
@ -182,10 +182,10 @@ describe('BrowserContext', function () {
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());
expect(context1.targets()).toHaveLength(1);
expect(context1.targets()[0]).toBe(page1.target());
expect(context2.targets()).toHaveLength(1);
expect(context2.targets()[0]).toBe(page2.target());
// Make sure pages don't share localstorage or cookies.
expect(
@ -211,20 +211,20 @@ describe('BrowserContext', function () {
// Cleanup contexts.
await Promise.all([context1.close(), context2.close()]);
expect(browser.browserContexts().length).toBe(1);
expect(browser.browserContexts()).toHaveLength(1);
});
it('should work across sessions', async () => {
const {browser, puppeteer} = getTestState();
expect(browser.browserContexts().length).toBe(1);
expect(browser.browserContexts()).toHaveLength(1);
const context = await browser.createIncognitoBrowserContext();
expect(browser.browserContexts().length).toBe(2);
expect(browser.browserContexts()).toHaveLength(2);
const remoteBrowser = await puppeteer.connect({
browserWSEndpoint: browser.wsEndpoint(),
});
const contexts = remoteBrowser.browserContexts();
expect(contexts.length).toBe(2);
expect(contexts).toHaveLength(2);
remoteBrowser.disconnect();
await context.close();
});
@ -232,11 +232,11 @@ describe('BrowserContext', function () {
it('should provide a context id', async () => {
const {browser} = getTestState();
expect(browser.browserContexts().length).toBe(1);
expect(browser.browserContexts()).toHaveLength(1);
expect(browser.browserContexts()[0]!.id).toBeUndefined();
const context = await browser.createIncognitoBrowserContext();
expect(browser.browserContexts().length).toBe(2);
expect(browser.browserContexts()).toHaveLength(2);
expect(browser.browserContexts()[1]!.id).toBeDefined();
await context.close();
});

View File

@ -22,6 +22,7 @@ import {
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
import {waitEvent} from './utils.js';
describe('Chromium-Specific Launcher tests', function () {
describe('Puppeteer.launch |browserURL| option', function () {
@ -107,7 +108,7 @@ describe('Chromium-Specific Launcher tests', function () {
const {defaultBrowserOptions, puppeteer} = getTestState();
const options = Object.assign({pipe: true}, defaultBrowserOptions);
const browser = await puppeteer.launch(options);
expect((await browser.pages()).length).toBe(1);
expect(await browser.pages()).toHaveLength(1);
expect(browser.wsEndpoint()).toBe('');
const page = await browser.newPage();
expect(await page.evaluate('11 * 11')).toBe(121);
@ -129,9 +130,7 @@ describe('Chromium-Specific Launcher tests', function () {
const {defaultBrowserOptions, puppeteer} = getTestState();
const options = Object.assign({pipe: true}, defaultBrowserOptions);
const browser = await puppeteer.launch(options);
const disconnectedEventPromise = new Promise(resolve => {
return browser.once('disconnected', resolve);
});
const disconnectedEventPromise = waitEvent(browser, 'disconnected');
// Emulate user exiting browser.
browser.process()!.kill();
await disconnectedEventPromise;

View File

@ -22,7 +22,7 @@ import {
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
import utils from './utils.js';
import {attachFrame} from './utils.js';
describe('Page.click', function () {
setupTestBrowserHooks();
@ -426,7 +426,7 @@ describe('Page.click', function () {
await page.goto(server.EMPTY_PAGE);
await page.setContent('<div style="width:100px;height:100px">spacer</div>');
await utils.attachFrame(
await attachFrame(
page,
'button-test',
server.PREFIX + '/input/button.html'
@ -449,7 +449,7 @@ describe('Page.click', function () {
await page.setContent(
'<div style="width:100px;height:2000px">spacer</div>'
);
await utils.attachFrame(
await attachFrame(
page,
'button-test',
server.CROSS_PROCESS_PREFIX + '/input/button.html'
@ -475,7 +475,7 @@ describe('Page.click', function () {
})
).toBe(5);
await page.setContent('<div style="width:100px;height:100px">spacer</div>');
await utils.attachFrame(
await attachFrame(
page,
'button-test',
server.PREFIX + '/input/button.html'

View File

@ -63,7 +63,7 @@ describe('Cookie specs', () => {
});
await page.goto(server.EMPTY_PAGE);
const cookies = await page.cookies();
expect(cookies.length).toBe(1);
expect(cookies).toHaveLength(1);
expect(cookies[0]!.httpOnly).toBe(true);
});
it('should properly report "Strict" sameSite cookie', async () => {
@ -74,7 +74,7 @@ describe('Cookie specs', () => {
});
await page.goto(server.EMPTY_PAGE);
const cookies = await page.cookies();
expect(cookies.length).toBe(1);
expect(cookies).toHaveLength(1);
expect(cookies[0]!.sameSite).toBe('Strict');
});
it('should properly report "Lax" sameSite cookie', async () => {
@ -85,7 +85,7 @@ describe('Cookie specs', () => {
});
await page.goto(server.EMPTY_PAGE);
const cookies = await page.cookies();
expect(cookies.length).toBe(1);
expect(cookies).toHaveLength(1);
expect(cookies[0]!.sameSite).toBe('Lax');
});
it('should get multiple cookies', async () => {
@ -212,8 +212,8 @@ describe('Cookie specs', () => {
const cookies1 = await page.cookies();
const cookies2 = await anotherPage.cookies();
expect(cookies1.length).toBe(1);
expect(cookies2.length).toBe(1);
expect(cookies1).toHaveLength(1);
expect(cookies2).toHaveLength(1);
expect(cookies1[0]!.name).toBe('page1cookie');
expect(cookies1[0]!.value).toBe('page1value');
expect(cookies2[0]!.name).toBe('page2cookie');

View File

@ -34,7 +34,7 @@ describe('Coverage specs', function () {
waitUntil: 'networkidle0',
});
const coverage = await page.coverage.stopJSCoverage();
expect(coverage.length).toBe(1);
expect(coverage).toHaveLength(1);
expect(coverage[0]!.url).toContain('/jscoverage/simple.html');
expect(coverage[0]!.ranges).toEqual([
{start: 0, end: 17},
@ -47,7 +47,7 @@ describe('Coverage specs', function () {
await page.coverage.startJSCoverage();
await page.goto(server.PREFIX + '/jscoverage/sourceurl.html');
const coverage = await page.coverage.stopJSCoverage();
expect(coverage.length).toBe(1);
expect(coverage).toHaveLength(1);
expect(coverage[0]!.url).toBe('nicename.js');
});
it('should ignore eval() scripts by default', async () => {
@ -56,7 +56,7 @@ describe('Coverage specs', function () {
await page.coverage.startJSCoverage();
await page.goto(server.PREFIX + '/jscoverage/eval.html');
const coverage = await page.coverage.stopJSCoverage();
expect(coverage.length).toBe(1);
expect(coverage).toHaveLength(1);
});
it("shouldn't ignore eval() scripts if reportAnonymousScripts is true", async () => {
const {page, server} = getTestState();
@ -69,7 +69,7 @@ describe('Coverage specs', function () {
return entry.url.startsWith('debugger://');
})
).not.toBe(null);
expect(coverage.length).toBe(2);
expect(coverage).toHaveLength(2);
});
it('should ignore pptr internal scripts if reportAnonymousScripts is true', async () => {
const {page, server} = getTestState();
@ -81,7 +81,7 @@ describe('Coverage specs', function () {
return console.log('bar');
});
const coverage = await page.coverage.stopJSCoverage();
expect(coverage.length).toBe(0);
expect(coverage).toHaveLength(0);
});
it('should report multiple scripts', async () => {
const {page, server} = getTestState();
@ -89,7 +89,7 @@ describe('Coverage specs', function () {
await page.coverage.startJSCoverage();
await page.goto(server.PREFIX + '/jscoverage/multiple.html');
const coverage = await page.coverage.stopJSCoverage();
expect(coverage.length).toBe(2);
expect(coverage).toHaveLength(2);
coverage.sort((a, b) => {
return a.url.localeCompare(b.url);
});
@ -102,9 +102,9 @@ describe('Coverage specs', function () {
await page.coverage.startJSCoverage();
await page.goto(server.PREFIX + '/jscoverage/ranges.html');
const coverage = await page.coverage.stopJSCoverage();
expect(coverage.length).toBe(1);
expect(coverage).toHaveLength(1);
const entry = coverage[0]!;
expect(entry.ranges.length).toBe(2);
expect(entry.ranges).toHaveLength(2);
const range1 = entry.ranges[0]!;
expect(entry.text.substring(range1.start, range1.end)).toBe('\n');
const range2 = entry.ranges[1]!;
@ -122,9 +122,9 @@ describe('Coverage specs', function () {
await page.coverage.startJSCoverage(coverageOptions);
await page.goto(server.PREFIX + '/jscoverage/ranges.html');
const coverage = await page.coverage.stopJSCoverage();
expect(coverage.length).toBe(1);
expect(coverage).toHaveLength(1);
const entry = coverage[0]!;
expect(entry.ranges.length).toBe(2);
expect(entry.ranges).toHaveLength(2);
const range1 = entry.ranges[0]!;
expect(entry.text.substring(range1.start, range1.end)).toBe('\n');
const range2 = entry.ranges[1]!;
@ -138,10 +138,10 @@ describe('Coverage specs', function () {
await page.coverage.startJSCoverage();
await page.goto(server.PREFIX + '/jscoverage/unused.html');
const coverage = await page.coverage.stopJSCoverage();
expect(coverage.length).toBe(1);
expect(coverage).toHaveLength(1);
const entry = coverage[0]!;
expect(entry.url).toContain('unused.html');
expect(entry.ranges.length).toBe(0);
expect(entry.ranges).toHaveLength(0);
});
it('should work with conditionals', async () => {
const {page, server} = getTestState();
@ -172,7 +172,7 @@ describe('Coverage specs', function () {
await page.goto(server.PREFIX + '/jscoverage/multiple.html');
await page.goto(server.EMPTY_PAGE);
const coverage = await page.coverage.stopJSCoverage();
expect(coverage.length).toBe(2);
expect(coverage).toHaveLength(2);
});
it('should NOT report scripts across navigations when enabled', async () => {
@ -182,7 +182,7 @@ describe('Coverage specs', function () {
await page.goto(server.PREFIX + '/jscoverage/multiple.html');
await page.goto(server.EMPTY_PAGE);
const coverage = await page.coverage.stopJSCoverage();
expect(coverage.length).toBe(0);
expect(coverage).toHaveLength(0);
});
});
describe('includeRawScriptCoverage', function () {
@ -193,7 +193,7 @@ describe('Coverage specs', function () {
waitUntil: 'networkidle0',
});
const coverage = await page.coverage.stopJSCoverage();
expect(coverage.length).toBe(1);
expect(coverage).toHaveLength(1);
expect(coverage[0]!.rawScriptCoverage).toBeUndefined();
});
it('should include rawScriptCoverage field when enabled', async () => {
@ -205,7 +205,7 @@ describe('Coverage specs', function () {
waitUntil: 'networkidle0',
});
const coverage = await page.coverage.stopJSCoverage();
expect(coverage.length).toBe(1);
expect(coverage).toHaveLength(1);
expect(coverage[0]!.rawScriptCoverage).toBeTruthy();
});
});
@ -232,7 +232,7 @@ describe('Coverage specs', function () {
await page.coverage.startCSSCoverage();
await page.goto(server.PREFIX + '/csscoverage/simple.html');
const coverage = await page.coverage.stopCSSCoverage();
expect(coverage.length).toBe(1);
expect(coverage).toHaveLength(1);
expect(coverage[0]!.url).toContain('/csscoverage/simple.html');
expect(coverage[0]!.ranges).toEqual([{start: 1, end: 22}]);
const range = coverage[0]!.ranges[0]!;
@ -246,7 +246,7 @@ describe('Coverage specs', function () {
await page.coverage.startCSSCoverage();
await page.goto(server.PREFIX + '/csscoverage/sourceurl.html');
const coverage = await page.coverage.stopCSSCoverage();
expect(coverage.length).toBe(1);
expect(coverage).toHaveLength(1);
expect(coverage[0]!.url).toBe('nicename.css');
});
it('should report multiple stylesheets', async () => {
@ -255,7 +255,7 @@ describe('Coverage specs', function () {
await page.coverage.startCSSCoverage();
await page.goto(server.PREFIX + '/csscoverage/multiple.html');
const coverage = await page.coverage.stopCSSCoverage();
expect(coverage.length).toBe(2);
expect(coverage).toHaveLength(2);
coverage.sort((a, b) => {
return a.url.localeCompare(b.url);
});
@ -268,9 +268,9 @@ describe('Coverage specs', function () {
await page.coverage.startCSSCoverage();
await page.goto(server.PREFIX + '/csscoverage/unused.html');
const coverage = await page.coverage.stopCSSCoverage();
expect(coverage.length).toBe(1);
expect(coverage).toHaveLength(1);
expect(coverage[0]!.url).toBe('unused.css');
expect(coverage[0]!.ranges.length).toBe(0);
expect(coverage[0]!.ranges).toHaveLength(0);
});
it('should work with media queries', async () => {
const {page, server} = getTestState();
@ -278,7 +278,7 @@ describe('Coverage specs', function () {
await page.coverage.startCSSCoverage();
await page.goto(server.PREFIX + '/csscoverage/media.html');
const coverage = await page.coverage.stopCSSCoverage();
expect(coverage.length).toBe(1);
expect(coverage).toHaveLength(1);
expect(coverage[0]!.url).toContain('/csscoverage/media.html');
expect(coverage[0]!.ranges).toEqual([{start: 8, end: 40}]);
});
@ -298,7 +298,7 @@ describe('Coverage specs', function () {
await page.coverage.startCSSCoverage();
await page.goto(server.PREFIX + '/csscoverage/empty.html');
const coverage = await page.coverage.stopCSSCoverage();
expect(coverage.length).toEqual(1);
expect(coverage).toHaveLength(1);
expect(coverage[0]!.text).toEqual('');
});
it('should ignore injected stylesheets', async () => {
@ -312,7 +312,7 @@ describe('Coverage specs', function () {
});
expect(margin).toBe('10px');
const coverage = await page.coverage.stopCSSCoverage();
expect(coverage.length).toBe(0);
expect(coverage).toHaveLength(0);
});
it('should work with a recently loaded stylesheet', async () => {
const {page, server} = getTestState();
@ -330,7 +330,7 @@ describe('Coverage specs', function () {
});
}, server.PREFIX + '/csscoverage/stylesheet1.css');
const coverage = await page.coverage.stopCSSCoverage();
expect(coverage.length).toBe(1);
expect(coverage).toHaveLength(1);
});
describe('resetOnNavigation', function () {
it('should report stylesheets across navigations', async () => {
@ -340,7 +340,7 @@ describe('Coverage specs', function () {
await page.goto(server.PREFIX + '/csscoverage/multiple.html');
await page.goto(server.EMPTY_PAGE);
const coverage = await page.coverage.stopCSSCoverage();
expect(coverage.length).toBe(2);
expect(coverage).toHaveLength(2);
});
it('should NOT report scripts across navigations', async () => {
const {page, server} = getTestState();
@ -349,7 +349,7 @@ describe('Coverage specs', function () {
await page.goto(server.PREFIX + '/csscoverage/multiple.html');
await page.goto(server.EMPTY_PAGE);
const coverage = await page.coverage.stopCSSCoverage();
expect(coverage.length).toBe(0);
expect(coverage).toHaveLength(0);
});
});
});

View File

@ -49,7 +49,7 @@ describe('Input.drag', function () {
const draggable = (await page.$('#drag'))!;
const data = await draggable.drag({x: 1, y: 1});
expect(data.items.length).toBe(1);
expect(data.items).toHaveLength(1);
expect(
await page.evaluate(() => {
return (globalThis as any).didDragStart;

View File

@ -25,7 +25,7 @@ import {
setupTestPageAndContextHooks,
shortWaitForArrayToHaveAtLeastNElements,
} from './mocha-utils.js';
import utils from './utils.js';
import {attachFrame} from './utils.js';
describe('ElementHandle specs', function () {
setupTestBrowserHooks();
@ -103,7 +103,7 @@ describe('ElementHandle specs', function () {
await page.goto(server.PREFIX + '/resetcss.html');
// Step 1: Add Frame and position it absolutely.
await utils.attachFrame(page, 'frame1', server.PREFIX + '/resetcss.html');
await attachFrame(page, 'frame1', server.PREFIX + '/resetcss.html');
await page.evaluate(() => {
const frame = document.querySelector<HTMLElement>('#frame1')!;
frame.style.position = 'absolute';
@ -134,19 +134,19 @@ describe('ElementHandle specs', function () {
const box = (await divHandle.boxModel())!;
expect(box.width).toBe(6);
expect(box.height).toBe(7);
expect(box.margin[0]!).toEqual({
expect(box.margin[0]).toEqual({
x: 1 + 4, // frame.left + div.left
y: 2 + 5,
});
expect(box.border[0]!).toEqual({
expect(box.border[0]).toEqual({
x: 1 + 4 + 3, // frame.left + div.left + div.margin-left
y: 2 + 5,
});
expect(box.padding[0]!).toEqual({
expect(box.padding[0]).toEqual({
x: 1 + 4 + 3 + 1, // frame.left + div.left + div.marginLeft + div.borderLeft
y: 2 + 5,
});
expect(box.content[0]!).toEqual({
expect(box.content[0]).toEqual({
x: 1 + 4 + 3 + 1 + 2, // frame.left + div.left + div.marginLeft + div.borderLeft + dif.paddingLeft
y: 2 + 5,
});
@ -166,10 +166,10 @@ describe('ElementHandle specs', function () {
const {page, server} = getTestState();
await page.goto(server.EMPTY_PAGE);
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
await attachFrame(page, 'frame1', server.EMPTY_PAGE);
const elementHandle = (await page.$('#frame1'))!;
const frame = await elementHandle.contentFrame();
expect(frame).toBe(page.frames()[1]!);
expect(frame).toBe(page.frames()[1]);
});
});
@ -737,7 +737,7 @@ describe('ElementHandle specs', function () {
expect(element).toBeDefined();
const elements = await page.$$('getByClass/foo');
expect(elements.length).toBe(3);
expect(elements).toHaveLength(3);
});
it('should eval when both queryOne and queryAll are registered', async () => {
const {page} = getTestState();

View File

@ -21,7 +21,7 @@ import {
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
import utils from './utils.js';
import {attachFrame} from './utils.js';
describe('Evaluation specs', function () {
setupTestBrowserHooks();
@ -418,7 +418,7 @@ describe('Evaluation specs', function () {
it('should throw if elementHandles are from other frames', async () => {
const {page, server} = getTestState();
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
await attachFrame(page, 'frame1', server.EMPTY_PAGE);
const bodyHandle = await page.frames()[1]!.$('body');
let error!: Error;
await page
@ -544,8 +544,8 @@ describe('Evaluation specs', function () {
const {page, server} = getTestState();
await page.goto(server.EMPTY_PAGE);
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
expect(page.frames().length).toBe(2);
await attachFrame(page, 'frame1', server.EMPTY_PAGE);
expect(page.frames()).toHaveLength(2);
await page.frames()[0]!.evaluate(() => {
return ((globalThis as any).FOO = 'foo');
});
@ -567,7 +567,7 @@ describe('Evaluation specs', function () {
const {page, server} = getTestState();
await page.goto(server.PREFIX + '/frames/one-frame.html');
expect(page.frames().length).toBe(2);
expect(page.frames()).toHaveLength(2);
expect(
await page.frames()[0]!.evaluate(() => {
return document.body.textContent!.trim();

View File

@ -21,6 +21,7 @@ import path from 'path';
import expect from 'expect';
import {getTestState} from './mocha-utils.js';
import {waitEvent} from './utils.js';
describe('Fixtures', function () {
it('dumpio option should work with pipe option', async () => {
@ -96,9 +97,7 @@ describe('Fixtures', function () {
browserWSEndpoint: await wsEndPointPromise,
});
const promises = [
new Promise(resolve => {
return browser.once('disconnected', resolve);
}),
waitEvent(browser, 'disconnected'),
new Promise(resolve => {
return res.on('close', resolve);
}),

View File

@ -23,7 +23,13 @@ import {
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
import utils, {dumpFrames} from './utils.js';
import {
attachFrame,
detachFrame,
dumpFrames,
navigateFrame,
waitEvent,
} from './utils.js';
describe('Frame specs', function () {
setupTestBrowserHooks();
@ -34,8 +40,8 @@ describe('Frame specs', function () {
const {page, server} = getTestState();
await page.goto(server.EMPTY_PAGE);
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
expect(page.frames().length).toBe(2);
await attachFrame(page, 'frame1', server.EMPTY_PAGE);
expect(page.frames()).toHaveLength(2);
const [frame1, frame2] = page.frames();
const context1 = await frame1!.executionContext();
const context2 = await frame2!.executionContext();
@ -83,12 +89,8 @@ describe('Frame specs', function () {
it('should throw for detached frames', async () => {
const {page, server} = getTestState();
const frame1 = (await utils.attachFrame(
page,
'frame1',
server.EMPTY_PAGE
))!;
await utils.detachFrame(page, 'frame1');
const frame1 = (await attachFrame(page, 'frame1', server.EMPTY_PAGE))!;
await detachFrame(page, 'frame1');
let error!: Error;
await frame1
.evaluate(() => {
@ -147,8 +149,8 @@ describe('Frame specs', function () {
page.on('frameattached', frame => {
return attachedFrames.push(frame);
});
await utils.attachFrame(page, 'frame1', './assets/frame.html');
expect(attachedFrames.length).toBe(1);
await attachFrame(page, 'frame1', './assets/frame.html');
expect(attachedFrames).toHaveLength(1);
expect(attachedFrames[0]!.url()).toContain('/assets/frame.html');
// validate framenavigated events
@ -156,8 +158,8 @@ describe('Frame specs', function () {
page.on('framenavigated', frame => {
return navigatedFrames.push(frame);
});
await utils.navigateFrame(page, 'frame1', './empty.html');
expect(navigatedFrames.length).toBe(1);
await navigateFrame(page, 'frame1', './empty.html');
expect(navigatedFrames).toHaveLength(1);
expect(navigatedFrames[0]!.url()).toBe(server.EMPTY_PAGE);
// validate framedetached events
@ -165,8 +167,8 @@ describe('Frame specs', function () {
page.on('framedetached', frame => {
return detachedFrames.push(frame);
});
await utils.detachFrame(page, 'frame1');
expect(detachedFrames.length).toBe(1);
await detachFrame(page, 'frame1');
expect(detachedFrames).toHaveLength(1);
expect(detachedFrames[0]!.isDetached()).toBe(true);
});
it('should send "framenavigated" when navigating on anchor URLs', async () => {
@ -175,7 +177,7 @@ describe('Frame specs', function () {
await page.goto(server.EMPTY_PAGE);
await Promise.all([
page.goto(server.EMPTY_PAGE + '#foo'),
utils.waitEvent(page, 'framenavigated'),
waitEvent(page, 'framenavigated'),
]);
expect(page.url()).toBe(server.EMPTY_PAGE + '#foo');
});
@ -203,9 +205,9 @@ describe('Frame specs', function () {
it('should detach child frames on navigation', async () => {
const {page, server} = getTestState();
let attachedFrames = [];
let detachedFrames = [];
let navigatedFrames = [];
let attachedFrames: Frame[] = [];
let detachedFrames: Frame[] = [];
let navigatedFrames: Frame[] = [];
page.on('frameattached', frame => {
return attachedFrames.push(frame);
});
@ -216,24 +218,24 @@ describe('Frame specs', function () {
return 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);
expect(attachedFrames).toHaveLength(4);
expect(detachedFrames).toHaveLength(0);
expect(navigatedFrames).toHaveLength(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);
expect(attachedFrames).toHaveLength(0);
expect(detachedFrames).toHaveLength(4);
expect(navigatedFrames).toHaveLength(1);
});
it('should support framesets', async () => {
const {page, server} = getTestState();
let attachedFrames = [];
let detachedFrames = [];
let navigatedFrames = [];
let attachedFrames: Frame[] = [];
let detachedFrames: Frame[] = [];
let navigatedFrames: Frame[] = [];
page.on('frameattached', frame => {
return attachedFrames.push(frame);
});
@ -244,17 +246,17 @@ describe('Frame specs', function () {
return 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);
expect(attachedFrames).toHaveLength(4);
expect(detachedFrames).toHaveLength(0);
expect(navigatedFrames).toHaveLength(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);
expect(attachedFrames).toHaveLength(0);
expect(detachedFrames).toHaveLength(4);
expect(navigatedFrames).toHaveLength(1);
});
it('should report frame from-inside shadow DOM', async () => {
const {page, server} = getTestState();
@ -268,13 +270,13 @@ describe('Frame specs', function () {
return (frame.onload = x);
});
}, server.EMPTY_PAGE);
expect(page.frames().length).toBe(2);
expect(page.frames()).toHaveLength(2);
expect(page.frames()[1]!.url()).toBe(server.EMPTY_PAGE);
});
it('should report frame.name()', async () => {
const {page, server} = getTestState();
await utils.attachFrame(page, 'theFrameId', server.EMPTY_PAGE);
await attachFrame(page, 'theFrameId', server.EMPTY_PAGE);
await page.evaluate((url: string) => {
const frame = document.createElement('iframe');
frame.name = 'theFrameName';
@ -291,8 +293,8 @@ describe('Frame specs', function () {
it('should report frame.parent()', async () => {
const {page, server} = getTestState();
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
await utils.attachFrame(page, 'frame2', server.EMPTY_PAGE);
await attachFrame(page, 'frame1', server.EMPTY_PAGE);
await 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());
@ -300,14 +302,14 @@ describe('Frame specs', function () {
it('should report different frame instance when frame re-attaches', async () => {
const {page, server} = getTestState();
const frame1 = await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
const frame1 = await attachFrame(page, 'frame1', server.EMPTY_PAGE);
await page.evaluate(() => {
(globalThis as any).frame = document.querySelector('#frame1');
(globalThis as any).frame.remove();
});
expect(frame1!.isDetached()).toBe(true);
const [frame2] = await Promise.all([
utils.waitEvent(page, 'frameattached'),
waitEvent(page, 'frameattached'),
page.evaluate(() => {
return document.body.appendChild((globalThis as any).frame);
}),
@ -320,7 +322,7 @@ describe('Frame specs', function () {
await page.goto(server.PREFIX + '/frames/one-frame-url-fragment.html');
expect(page.frames().length).toBe(2);
expect(page.frames()).toHaveLength(2);
expect(page.frames()[1]!.url()).toBe(
server.PREFIX + '/frames/frame.html?param=value#fragment'
);

View File

@ -95,7 +95,7 @@ describe('ignoreHTTPSErrors', function () {
httpsServer.waitForRequest('/plzredirect'),
page.goto(httpsServer.PREFIX + '/plzredirect'),
]);
expect(responses.length).toBe(2);
expect(responses).toHaveLength(2);
expect(responses[0]!.status()).toBe(302);
const securityDetails = responses[0]!.securityDetails()!;
const protocol = (serverRequest.socket as TLSSocket)
@ -134,7 +134,7 @@ describe('ignoreHTTPSErrors', function () {
await page.goto(httpsServer.PREFIX + '/mixedcontent.html', {
waitUntil: 'load',
});
expect(page.frames().length).toBe(2);
expect(page.frames()).toHaveLength(2);
// Make sure blocked iframe has functional execution context
// @see https://github.com/puppeteer/puppeteer/issues/2709
expect(await page.frames()[0]!.evaluate('1 + 2')).toBe(3);

View File

@ -24,6 +24,7 @@ import {
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
import {waitEvent} from './utils.js';
const FILE_TO_UPLOAD = path.join(__dirname, '/../assets/file-to-upload.txt');
@ -174,9 +175,7 @@ describe('input tests', function () {
]);
await Promise.all([
chooser.accept([FILE_TO_UPLOAD]),
new Promise(x => {
return page.once('metrics', x);
}),
waitEvent(page, 'metrics'),
]);
expect(
await page.$eval('input', input => {

View File

@ -24,7 +24,7 @@ import {
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
import utils from './utils.js';
import {attachFrame} from './utils.js';
describe('Keyboard', function () {
setupTestBrowserHooks();
@ -503,7 +503,7 @@ describe('Keyboard', function () {
const {page, server} = getTestState();
await page.goto(server.EMPTY_PAGE);
await utils.attachFrame(
await attachFrame(
page,
'emoji-test',
server.PREFIX + '/input/textarea.html'

View File

@ -27,7 +27,7 @@ import {rmSync} from 'puppeteer-core/internal/node/util/fs.js';
import sinon from 'sinon';
import {getTestState, itOnlyRegularInstall} from './mocha-utils.js';
import utils from './utils.js';
import {dumpFrames, waitEvent} from './utils.js';
const TMP_FOLDER = path.join(os.tmpdir(), 'pptr_tmp_folder-');
const FIREFOX_TIMEOUT = 30 * 1000;
@ -258,12 +258,12 @@ describe('Launcher specs', function () {
puppeteer.configuration.temporaryDirectory = testTmpDir;
// Path should be empty before starting the browser.
expect(fs.readdirSync(testTmpDir).length).toEqual(0);
expect(fs.readdirSync(testTmpDir)).toHaveLength(0);
const browser = await puppeteer.launch(defaultBrowserOptions);
// One profile folder should have been created at this moment.
const profiles = fs.readdirSync(testTmpDir);
expect(profiles.length).toEqual(1);
expect(profiles).toHaveLength(1);
expect(profiles[0]?.startsWith('puppeteer_dev_chrome_profile-')).toBe(
true
);
@ -272,7 +272,7 @@ describe('Launcher specs', function () {
await browser.newPage();
await browser.close();
// Profile should be deleted after closing the browser
expect(fs.readdirSync(testTmpDir).length).toEqual(0);
expect(fs.readdirSync(testTmpDir)).toHaveLength(0);
// Restore env var
puppeteer.configuration.temporaryDirectory = oldTmpDir;
@ -523,7 +523,7 @@ describe('Launcher specs', function () {
options.args = [server.EMPTY_PAGE].concat(options.args || []);
const browser = await puppeteer.launch(options);
const pages = await browser.pages();
expect(pages.length).toBe(1);
expect(pages).toHaveLength(1);
const page = pages[0]!;
if (page.url() !== server.EMPTY_PAGE) {
await page.waitForNavigation();
@ -628,7 +628,7 @@ describe('Launcher specs', function () {
};
const browser = await puppeteer.launch(options);
const pages = await browser.pages();
expect(pages.length).toBe(0);
expect(pages).toHaveLength(0);
await browser.close();
});
});
@ -684,7 +684,7 @@ describe('Launcher specs', function () {
browserWSEndpoint: originalBrowser.wsEndpoint(),
});
await Promise.all([
utils.waitEvent(originalBrowser, 'disconnected'),
waitEvent(originalBrowser, 'disconnected'),
remoteBrowser.close(),
]);
});
@ -702,7 +702,7 @@ describe('Launcher specs', function () {
browserWSEndpoint: originalBrowser.wsEndpoint(),
});
await Promise.all([
utils.waitEvent(originalBrowser, 'disconnected'),
waitEvent(originalBrowser, 'disconnected'),
remoteBrowser.close(),
]);
});
@ -746,7 +746,7 @@ describe('Launcher specs', function () {
});
try {
const targets = browser.targets();
expect(targets.length).toEqual(1);
expect(targets).toHaveLength(1);
expect(
targets.find(target => {
return target.type() === 'page';
@ -806,7 +806,7 @@ describe('Launcher specs', function () {
const restoredPage = pages.find(page => {
return page.url() === server.PREFIX + '/frames/nested-frames.html';
})!;
expect(utils.dumpFrames(restoredPage.mainFrame())).toEqual([
expect(dumpFrames(restoredPage.mainFrame())).toEqual([
'http://localhost:<PORT>/frames/nested-frames.html',
' http://localhost:<PORT>/frames/two-frames.html (2frames)',
' http://localhost:<PORT>/frames/frame.html (uno)',
@ -1024,7 +1024,7 @@ describe('Launcher specs', function () {
});
await Promise.all([
utils.waitEvent(remoteBrowser2, 'disconnected'),
waitEvent(remoteBrowser2, 'disconnected'),
remoteBrowser2.disconnect(),
]);
@ -1033,8 +1033,8 @@ describe('Launcher specs', function () {
expect(disconnectedRemote2).toBe(1);
await Promise.all([
utils.waitEvent(remoteBrowser1, 'disconnected'),
utils.waitEvent(originalBrowser, 'disconnected'),
waitEvent(remoteBrowser1, 'disconnected'),
waitEvent(originalBrowser, 'disconnected'),
originalBrowser.close(),
]);

View File

@ -14,8 +14,8 @@
* limitations under the License.
*/
import * as fs from 'fs';
import * as path from 'path';
import fs from 'fs';
import path from 'path';
import {TestServer} from '@pptr/testserver';
import {Protocol} from 'devtools-protocol';

View File

@ -184,9 +184,9 @@ describe('navigation', function () {
expect(error.message).toContain('SSL_ERROR_UNKNOWN');
}
expect(requests.length).toBe(2);
expect(requests[0]!).toBe('request');
expect(requests[1]!).toBe('requestfailed');
expect(requests).toHaveLength(2);
expect(requests[0]).toBe('request');
expect(requests[1]).toBe('requestfailed');
});
it('should fail when navigating to bad SSL after redirects', async () => {
const {page, server, httpsServer, isChrome} = getTestState();
@ -383,9 +383,7 @@ describe('navigation', function () {
});
// Wait for the page's 'load' event.
await new Promise(fulfill => {
return page.once('load', fulfill);
});
await waitEvent(page, 'load');
expect(navigationFinished).toBe(false);
// Wait for the initial three resources to be requested.
@ -482,7 +480,7 @@ describe('navigation', function () {
const dataURL = 'data:text/html,<div>yo</div>';
const response = (await page.goto(dataURL))!;
expect(response.status()).toBe(200);
expect(requests.length).toBe(1);
expect(requests).toHaveLength(1);
expect(requests[0]!.url()).toBe(dataURL);
});
it('should navigate to URL with hash and fire requests without hash', async () => {
@ -495,7 +493,7 @@ describe('navigation', function () {
const response = (await page.goto(server.EMPTY_PAGE + '#hash'))!;
expect(response.status()).toBe(200);
expect(response.url()).toBe(server.EMPTY_PAGE);
expect(requests.length).toBe(1);
expect(requests).toHaveLength(1);
expect(requests[0]!.url()).toBe(server.EMPTY_PAGE);
});
it('should work with self requesting page', async () => {
@ -677,12 +675,8 @@ describe('navigation', function () {
server.PREFIX + '/frames/one-frame.html'
);
const frame = await waitEvent(page, 'frameattached');
await new Promise<void>(fulfill => {
page.on('framenavigated', f => {
if (f === frame) {
fulfill();
}
});
await waitEvent(page, 'framenavigated', f => {
return f === frame;
});
await Promise.all([
frame.evaluate(() => {
@ -740,7 +734,7 @@ describe('navigation', function () {
const response = (await page.frames()[1]!.goto(server.EMPTY_PAGE))!;
expect(response.ok()).toBe(true);
expect(response.frame()).toBe(page.frames()[1]!);
expect(response.frame()).toBe(page.frames()[1]);
});
it('should reject when frame detaches', async () => {
const {page, server} = getTestState();

View File

@ -27,7 +27,7 @@ import {
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
import {attachFrame, isFavicon} from './utils.js';
import {attachFrame, isFavicon, waitEvent} from './utils.js';
describe('network', function () {
setupTestBrowserHooks();
@ -42,7 +42,7 @@ describe('network', function () {
return !isFavicon(request) && requests.push(request);
});
await page.goto(server.EMPTY_PAGE);
expect(requests.length).toBe(1);
expect(requests).toHaveLength(1);
});
it('should fire for iframes', async () => {
const {page, server} = getTestState();
@ -53,7 +53,7 @@ describe('network', function () {
});
await page.goto(server.EMPTY_PAGE);
await attachFrame(page, 'frame1', server.EMPTY_PAGE);
expect(requests.length).toBe(2);
expect(requests).toHaveLength(2);
});
it('should fire for fetches', async () => {
const {page, server} = getTestState();
@ -66,7 +66,7 @@ describe('network', function () {
await page.evaluate(() => {
return fetch('/empty.html');
});
expect(requests.length).toBe(2);
expect(requests).toHaveLength(2);
});
});
describe('Request.frame', function () {
@ -78,7 +78,7 @@ describe('network', function () {
return !isFavicon(request) && requests.push(request);
});
await page.goto(server.EMPTY_PAGE);
expect(requests.length).toBe(1);
expect(requests).toHaveLength(1);
expect(requests[0]!.frame()).toBe(page.mainFrame());
});
it('should work for subframe navigation request', async () => {
@ -90,8 +90,8 @@ describe('network', function () {
return !isFavicon(request) && requests.push(request);
});
await attachFrame(page, 'frame1', server.EMPTY_PAGE);
expect(requests.length).toBe(1);
expect(requests[0]!.frame()).toBe(page.frames()[1]!);
expect(requests).toHaveLength(1);
expect(requests[0]!.frame()).toBe(page.frames()[1]);
});
it('should work for fetch requests', async () => {
const {page, server} = getTestState();
@ -107,7 +107,7 @@ describe('network', function () {
requests = requests.filter(request => {
return !request.url().includes('favicon');
});
expect(requests.length).toBe(1);
expect(requests).toHaveLength(1);
expect(requests[0]!.frame()).toBe(page.mainFrame());
});
});
@ -256,18 +256,19 @@ describe('network', function () {
server.setRoute('/post', (_req, res) => {
return res.end();
});
let request!: HTTPRequest;
page.on('request', r => {
if (!isFavicon(r)) {
request = r;
}
});
await page.evaluate(() => {
return fetch('./post', {
method: 'POST',
body: JSON.stringify({foo: 'bar'}),
});
});
const [request] = await Promise.all([
waitEvent<HTTPRequest>(page, 'request', r => {
return !isFavicon(r);
}),
page.evaluate(() => {
return fetch('./post', {
method: 'POST',
body: JSON.stringify({foo: 'bar'}),
});
}),
]);
expect(request).toBeTruthy();
expect(request.postData()).toBe('{"foo":"bar"}');
});
@ -302,7 +303,7 @@ describe('network', function () {
server.setRedirect('/foo.html', '/empty.html');
const response = (await page.goto(server.PREFIX + '/foo.html'))!;
const redirectChain = response.request().redirectChain();
expect(redirectChain.length).toBe(1);
expect(redirectChain).toHaveLength(1);
const redirected = redirectChain[0]!.response()!;
expect(redirected.status()).toBe(302);
let error!: Error;
@ -404,17 +405,16 @@ describe('network', function () {
res.end('Hello World');
});
const url = server.CROSS_PROCESS_PREFIX + '/test.html';
const responsePromise = new Promise<HTTPResponse>(resolve => {
page.on('response', response => {
const responsePromise = waitEvent<HTTPResponse>(
page,
'response',
response => {
// Get the preflight response.
if (
response.request().method() === 'OPTIONS' &&
response.url() === url
) {
resolve(response);
}
});
});
return (
response.request().method() === 'OPTIONS' && response.url() === url
);
}
);
// Trigger a request with a preflight.
await page.evaluate(async src => {
@ -464,7 +464,7 @@ describe('network', function () {
return responses.push(response);
});
await page.goto(server.EMPTY_PAGE);
expect(responses.length).toBe(1);
expect(responses).toHaveLength(1);
expect(responses[0]!.timing()!.receiveHeadersEnd).toBeGreaterThan(0);
});
});
@ -478,7 +478,7 @@ describe('network', function () {
return requests.push(request);
});
await page.goto(server.EMPTY_PAGE);
expect(requests.length).toBe(1);
expect(requests).toHaveLength(1);
expect(requests[0]!.url()).toBe(server.EMPTY_PAGE);
expect(requests[0]!.resourceType()).toBe('document');
expect(requests[0]!.method()).toBe('GET');
@ -508,7 +508,7 @@ describe('network', function () {
return responses.push(response);
});
await page.goto(server.EMPTY_PAGE);
expect(responses.length).toBe(1);
expect(responses).toHaveLength(1);
expect(responses[0]!.url()).toBe(server.EMPTY_PAGE);
expect(responses[0]!.status()).toBe(200);
expect(responses[0]!.ok()).toBe(true);
@ -537,7 +537,7 @@ describe('network', function () {
return failedRequests.push(request);
});
await page.goto(server.PREFIX + '/one-style.html');
expect(failedRequests.length).toBe(1);
expect(failedRequests).toHaveLength(1);
expect(failedRequests[0]!.url()).toContain('one-style.css');
expect(failedRequests[0]!.response()).toBe(null);
expect(failedRequests[0]!.resourceType()).toBe('stylesheet');
@ -558,7 +558,7 @@ describe('network', function () {
return requests.push(request);
});
await page.goto(server.EMPTY_PAGE);
expect(requests.length).toBe(1);
expect(requests).toHaveLength(1);
expect(requests[0]!.url()).toBe(server.EMPTY_PAGE);
expect(requests[0]!.response()).toBeTruthy();
expect(requests[0]!.frame() === page.mainFrame()).toBe(true);
@ -610,7 +610,7 @@ describe('network', function () {
// Check redirect chain
const redirectChain = response.request().redirectChain();
expect(redirectChain.length).toBe(1);
expect(redirectChain).toHaveLength(1);
expect(redirectChain[0]!.url()).toContain('/foo.html');
expect(redirectChain[0]!.response()!.remoteAddress().port).toBe(
server.PORT
@ -812,11 +812,7 @@ describe('network', function () {
res.end('hello world');
});
const responsePromise = new Promise<HTTPResponse>(resolve => {
return page.on('response', response => {
return resolve(response);
});
});
const responsePromise = waitEvent<HTTPResponse>(page, 'response');
page.evaluate(() => {
const xhr = new XMLHttpRequest();
xhr.open('GET', '/foo');
@ -847,18 +843,16 @@ describe('network', function () {
});
await page.goto(httpsServer.PREFIX + '/setcookie.html');
const url = httpsServer.CROSS_PROCESS_PREFIX + '/setcookie.html';
const response = await new Promise<HTTPResponse>(resolve => {
page.on('response', response => {
if (response.url() === url) {
resolve(response);
}
});
const [response] = await Promise.all([
waitEvent<HTTPResponse>(page, 'response', response => {
return response.url() === url;
}),
page.evaluate(src => {
const xhr = new XMLHttpRequest();
xhr.open('GET', src);
xhr.send();
}, url);
});
}, url),
]);
expect(response.headers()['set-cookie']).toBe(setCookieString);
} finally {
await page.close();

View File

@ -20,7 +20,7 @@ import {BrowserContext} from 'puppeteer-core/internal/api/BrowserContext.js';
import {Page} from 'puppeteer-core/internal/api/Page.js';
import {describeWithDebugLogs, getTestState} from './mocha-utils.js';
import utils from './utils.js';
import {attachFrame, detachFrame, navigateFrame} from './utils.js';
describeWithDebugLogs('OOPIF', function () {
/* We use a special browser for this test as we need the --site-per-process flag */
@ -61,8 +61,8 @@ describeWithDebugLogs('OOPIF', function () {
const framePromise = page.waitForFrame(frame => {
return frame.url().endsWith('/empty.html');
});
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
await utils.attachFrame(
await attachFrame(page, 'frame1', server.EMPTY_PAGE);
await attachFrame(
page,
'frame2',
server.CROSS_PROCESS_PREFIX + '/empty.html'
@ -77,14 +77,14 @@ describeWithDebugLogs('OOPIF', function () {
const framePromise = page.waitForFrame(frame => {
return page.frames().indexOf(frame) === 1;
});
await utils.attachFrame(
await attachFrame(
page,
'frame1',
server.CROSS_PROCESS_PREFIX + '/empty.html'
);
const frame = await framePromise;
expect(frame.url()).toContain('/empty.html');
await utils.navigateFrame(
await navigateFrame(
page,
'frame1',
server.CROSS_PROCESS_PREFIX + '/assets/frame.html'
@ -98,17 +98,17 @@ describeWithDebugLogs('OOPIF', function () {
const framePromise = page.waitForFrame(frame => {
return page.frames().indexOf(frame) === 1;
});
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
await attachFrame(page, 'frame1', server.EMPTY_PAGE);
const frame = await framePromise;
expect(frame.isOOPFrame()).toBe(false);
await utils.navigateFrame(
await navigateFrame(
page,
'frame1',
server.CROSS_PROCESS_PREFIX + '/empty.html'
);
expect(frame.isOOPFrame()).toBe(true);
await utils.navigateFrame(page, 'frame1', server.EMPTY_PAGE);
await navigateFrame(page, 'frame1', server.EMPTY_PAGE);
expect(frame.isOOPFrame()).toBe(false);
expect(page.frames()).toHaveLength(2);
});
@ -122,7 +122,7 @@ describeWithDebugLogs('OOPIF', function () {
const frame2Promise = page.waitForFrame(frame => {
return page.frames().indexOf(frame) === 2;
});
await utils.attachFrame(
await attachFrame(
page,
'frame1',
server.CROSS_PROCESS_PREFIX + '/frames/one-frame.html'
@ -148,17 +148,17 @@ describeWithDebugLogs('OOPIF', function () {
const framePromise = page.waitForFrame(frame => {
return page.frames().indexOf(frame) === 1;
});
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
await attachFrame(page, 'frame1', server.EMPTY_PAGE);
const frame = await framePromise;
expect(frame.isOOPFrame()).toBe(false);
await utils.navigateFrame(
await navigateFrame(
page,
'frame1',
server.CROSS_PROCESS_PREFIX + '/empty.html'
);
expect(frame.isOOPFrame()).toBe(true);
await utils.detachFrame(page, 'frame1');
await detachFrame(page, 'frame1');
expect(page.frames()).toHaveLength(1);
});
@ -169,19 +169,19 @@ describeWithDebugLogs('OOPIF', function () {
const framePromise = page.waitForFrame(frame => {
return page.frames().indexOf(frame) === 1;
});
await utils.attachFrame(page, 'frame1', server.EMPTY_PAGE);
await attachFrame(page, 'frame1', server.EMPTY_PAGE);
const frame = await framePromise;
expect(frame.isOOPFrame()).toBe(false);
const nav = frame.waitForNavigation();
await utils.navigateFrame(
await navigateFrame(
page,
'frame1',
server.CROSS_PROCESS_PREFIX + '/empty.html'
);
await nav;
expect(frame.isOOPFrame()).toBe(true);
await utils.detachFrame(page, 'frame1');
await detachFrame(page, 'frame1');
expect(page.frames()).toHaveLength(1);
});
@ -192,14 +192,14 @@ describeWithDebugLogs('OOPIF', function () {
const framePromise = page.waitForFrame(frame => {
return page.frames().indexOf(frame) === 1;
});
await utils.attachFrame(
await attachFrame(
page,
'frame1',
server.CROSS_PROCESS_PREFIX + '/empty.html'
);
const frame = await framePromise;
expect(frame.url()).toContain('/empty.html');
await utils.navigateFrame(page, 'frame1', server.EMPTY_PAGE);
await navigateFrame(page, 'frame1', server.EMPTY_PAGE);
expect(frame.url()).toBe(server.EMPTY_PAGE);
});
@ -210,7 +210,7 @@ describeWithDebugLogs('OOPIF', function () {
const framePromise = page.waitForFrame(frame => {
return page.frames().indexOf(frame) === 1;
});
await utils.attachFrame(
await attachFrame(
page,
'frame1',
server.CROSS_PROCESS_PREFIX + '/empty.html'
@ -249,7 +249,7 @@ describeWithDebugLogs('OOPIF', function () {
const framePromise = page.waitForFrame(frame => {
return page.frames().indexOf(frame) === 1;
});
await utils.attachFrame(
await attachFrame(
page,
'frame1',
server.CROSS_PROCESS_PREFIX + '/empty.html'
@ -282,8 +282,8 @@ describeWithDebugLogs('OOPIF', function () {
});
await page.goto(server.PREFIX + '/dynamic-oopif.html');
await frame;
expect(oopifs(context).length).toBe(1);
expect(page.frames().length).toBe(2);
expect(oopifs(context)).toHaveLength(1);
expect(page.frames()).toHaveLength(2);
});
it('should wait for inner OOPIFs', async () => {
@ -292,12 +292,12 @@ describeWithDebugLogs('OOPIF', function () {
const frame2 = await page.waitForFrame(frame => {
return frame.url().endsWith('inner-frame2.html');
});
expect(oopifs(context).length).toBe(2);
expect(oopifs(context)).toHaveLength(2);
expect(
page.frames().filter(frame => {
return frame.isOOPFrame();
}).length
).toBe(2);
})
).toHaveLength(2);
expect(
await frame2.evaluate(() => {
return document.querySelectorAll('button').length;
@ -317,7 +317,7 @@ describeWithDebugLogs('OOPIF', function () {
});
await page.goto(server.PREFIX + '/dynamic-oopif.html');
await frame;
expect(oopifs(context).length).toBe(1);
expect(oopifs(context)).toHaveLength(1);
});
it('should support frames within OOP iframes', async () => {
const {server} = getTestState();
@ -327,7 +327,7 @@ describeWithDebugLogs('OOPIF', function () {
});
await page.goto(server.PREFIX + '/dynamic-oopif.html');
const oopIframe = await oopIframePromise;
await utils.attachFrame(
await attachFrame(
oopIframe,
'frame1',
server.CROSS_PROCESS_PREFIX + '/empty.html'
@ -335,7 +335,7 @@ describeWithDebugLogs('OOPIF', function () {
const frame1 = oopIframe.childFrames()[0]!;
expect(frame1.url()).toMatch(/empty.html$/);
await utils.navigateFrame(
await navigateFrame(
oopIframe,
'frame1',
server.CROSS_PROCESS_PREFIX + '/oopif.html'
@ -346,7 +346,7 @@ describeWithDebugLogs('OOPIF', function () {
{waitUntil: 'load'}
);
expect(frame1.url()).toMatch(/oopif.html#navigate-within-document$/);
await utils.detachFrame(oopIframe, 'frame1');
await detachFrame(oopIframe, 'frame1');
expect(oopIframe.childFrames()).toHaveLength(0);
});
@ -356,7 +356,7 @@ describeWithDebugLogs('OOPIF', function () {
const framePromise = page.waitForFrame(frame => {
return page.frames().indexOf(frame) === 1;
});
await utils.attachFrame(
await attachFrame(
page,
'frame1',
server.CROSS_PROCESS_PREFIX + '/empty.html'
@ -404,8 +404,8 @@ describeWithDebugLogs('OOPIF', function () {
});
await page.goto(server.PREFIX + '/dynamic-oopif.html');
await frame;
expect(oopifs(context).length).toBe(1);
expect(page.frames().length).toBe(2);
expect(oopifs(context)).toHaveLength(1);
expect(page.frames()).toHaveLength(2);
const browserURL = 'http://127.0.0.1:21222';
const browser1 = await puppeteer.connect({browserURL});
@ -434,7 +434,7 @@ describeWithDebugLogs('OOPIF', function () {
const {server} = getTestState();
await page.goto(server.EMPTY_PAGE);
await utils.attachFrame(
await attachFrame(
page,
'frame2',
server.CROSS_PROCESS_PREFIX + '/empty.html'

View File

@ -185,16 +185,16 @@ describe('Page', function () {
it('should throw when page crashes', async () => {
const {page, isChrome} = getTestState();
let error!: Error;
page.on('error', err => {
return (error = err);
});
let navigate: Promise<unknown>;
if (isChrome) {
page.goto('chrome://crash').catch(() => {});
navigate = page.goto('chrome://crash').catch(() => {});
} else {
page.goto('about:crashcontent').catch(() => {});
navigate = page.goto('about:crashcontent').catch(() => {});
}
await waitEvent(page, 'error');
const [error] = await Promise.all([
waitEvent<Error>(page, 'error'),
navigate,
]);
expect(error.message).toBe('Page crashed!');
});
});
@ -204,9 +204,7 @@ describe('Page', function () {
const {page} = getTestState();
const [popup] = await Promise.all([
new Promise<Page>(x => {
return page.once('popup', x);
}),
waitEvent<Page>(page, 'popup'),
page.evaluate(() => {
return window.open('about:blank');
}),
@ -226,9 +224,7 @@ describe('Page', function () {
const {page} = getTestState();
const [popup] = await Promise.all([
new Promise<Page>(x => {
return page.once('popup', x);
}),
waitEvent<Page>(page, 'popup'),
page.evaluate(() => {
return window.open('about:blank', undefined, 'noopener');
}),
@ -250,9 +246,7 @@ describe('Page', function () {
await page.goto(server.EMPTY_PAGE);
await page.setContent('<a target=_blank href="/one-style.html">yo</a>');
const [popup] = await Promise.all([
new Promise<Page>(x => {
return page.once('popup', x);
}),
waitEvent<Page>(page, 'popup'),
page.click('a'),
]);
expect(
@ -274,9 +268,7 @@ describe('Page', function () {
'<a target=_blank rel=opener href="/one-style.html">yo</a>'
);
const [popup] = await Promise.all([
new Promise<Page>(x => {
return page.once('popup', x);
}),
waitEvent<Page>(page, 'popup'),
page.click('a'),
]);
expect(
@ -298,9 +290,7 @@ describe('Page', function () {
'<a target=_blank rel=noopener href="/one-style.html">yo</a>'
);
const [popup] = await Promise.all([
new Promise<Page>(x => {
return page.once('popup', x);
}),
waitEvent<Page>(page, 'popup'),
page.$eval('a', a => {
return (a as HTMLAnchorElement).click();
}),
@ -324,9 +314,7 @@ describe('Page', function () {
'<a target=_blank rel=noopener href="/one-style.html">yo</a>'
);
const [popup] = await Promise.all([
new Promise<Page>(x => {
return page.once('popup', x);
}),
waitEvent<Page>(page, 'popup'),
page.click('a'),
]);
expect(
@ -642,15 +630,11 @@ describe('Page', function () {
it('should work', async () => {
const {page} = getTestState();
let message!: ConsoleMessage;
page.once('console', m => {
return (message = m);
});
await Promise.all([
const [message] = await Promise.all([
waitEvent<ConsoleMessage>(page, 'console'),
page.evaluate(() => {
return console.log('hello', 5, {foo: 'bar'});
}),
waitEvent(page, 'console'),
]);
expect(message.text()).toEqual('hello 5 JSHandle@object');
expect(message.type()).toEqual('log');
@ -720,15 +704,11 @@ describe('Page', function () {
it('should not fail for window object', async () => {
const {page} = getTestState();
let message!: ConsoleMessage;
page.once('console', msg => {
return (message = msg);
});
await Promise.all([
const [message] = await Promise.all([
waitEvent<ConsoleMessage>(page, 'console'),
page.evaluate(() => {
return console.error(window);
}),
waitEvent(page, 'console'),
]);
expect(message.text()).toBe('JSHandle@object');
});
@ -854,11 +834,11 @@ describe('Page', function () {
it('metrics event fired on console.timeStamp', async () => {
const {page} = getTestState();
const metricsPromise = new Promise<{metrics: Metrics; title: string}>(
fulfill => {
return page.once('metrics', fulfill);
}
const metricsPromise = waitEvent<{metrics: Metrics; title: string}>(
page,
'metrics'
);
await page.evaluate(() => {
return console.timeStamp('test42');
});
@ -1342,13 +1322,9 @@ describe('Page', function () {
it('should fire', async () => {
const {page, server} = getTestState();
let error!: Error;
page.once('pageerror', e => {
return (error = e);
});
await Promise.all([
const [error] = await Promise.all([
waitEvent<Error>(page, 'pageerror'),
page.goto(server.PREFIX + '/error.html'),
waitEvent(page, 'pageerror'),
]);
expect(error.message).toContain('Fancy');
});
@ -2220,7 +2196,7 @@ describe('Page', function () {
'black',
'magenta'
);
expect(result.length).toEqual(1);
expect(result).toHaveLength(1);
});
it('should return [] on no values', async () => {
const {page, server} = getTestState();
@ -2313,9 +2289,7 @@ describe('Page', function () {
return ((window as any)['newPage'] = window.open('about:blank'));
});
const newPage = await newPagePromise;
const closedPromise = new Promise(x => {
return newPage.on('close', x);
});
const closedPromise = waitEvent(newPage, 'close');
await page.evaluate(() => {
return (window as any)['newPage'].close();
});
@ -2325,9 +2299,7 @@ describe('Page', function () {
const {context} = getTestState();
const newPage = await context.newPage();
const closedPromise = new Promise(x => {
return newPage.on('close', x);
});
const closedPromise = waitEvent(newPage, 'close');
await newPage.close();
await closedPromise;
});

View File

@ -106,13 +106,13 @@ describe('Query handler tests', function () {
await page.setContent('<section>test</section>');
expect(await page.$('text/test')).toBeTruthy();
expect((await page.$$('text/test')).length).toBe(1);
expect(await page.$$('text/test')).toHaveLength(1);
});
it('should return empty array for non-existing element', async () => {
const {page} = getTestState();
expect(await page.$('text/test')).toBeFalsy();
expect((await page.$$('text/test')).length).toBe(0);
expect(await page.$$('text/test')).toHaveLength(0);
});
it('should return first element', async () => {
const {page} = getTestState();
@ -132,7 +132,7 @@ describe('Query handler tests', function () {
await page.setContent('<div>a</div><div>a</div>');
const elements = await page.$$('text/a');
expect(elements.length).toBe(2);
expect(elements).toHaveLength(2);
});
it('should pierce shadow DOM', async () => {
const {page} = getTestState();
@ -277,7 +277,7 @@ describe('Query handler tests', function () {
const elementHandle = (await page.$('div'))!;
expect(await elementHandle.$(`text/a`)).toBeTruthy();
expect((await elementHandle.$$(`text/a`)).length).toBe(1);
expect(await elementHandle.$$(`text/a`)).toHaveLength(1);
});
it('should return null for non-existing element', async () => {
@ -287,7 +287,7 @@ describe('Query handler tests', function () {
const elementHandle = (await page.$('div'))!;
expect(await elementHandle.$(`text/a`)).toBeFalsy();
expect((await elementHandle.$$(`text/a`)).length).toBe(0);
expect(await elementHandle.$$(`text/a`)).toHaveLength(0);
});
});
});
@ -300,7 +300,7 @@ describe('Query handler tests', function () {
await page.setContent('<section>test</section>');
expect(await page.$('xpath/html/body/section')).toBeTruthy();
expect((await page.$$('xpath/html/body/section')).length).toBe(1);
expect(await page.$$('xpath/html/body/section')).toHaveLength(1);
});
it('should return empty array for non-existing element', async () => {
const {page} = getTestState();
@ -309,8 +309,8 @@ describe('Query handler tests', function () {
await page.$('xpath/html/body/non-existing-element')
).toBeFalsy();
expect(
(await page.$$('xpath/html/body/non-existing-element')).length
).toBe(0);
await page.$$('xpath/html/body/non-existing-element')
).toHaveLength(0);
});
it('should return first element', async () => {
const {page} = getTestState();
@ -330,7 +330,7 @@ describe('Query handler tests', function () {
await page.setContent('<div></div><div></div>');
const elements = await page.$$('xpath/html/body/div');
expect(elements.length).toBe(2);
expect(elements).toHaveLength(2);
});
});
describe('in ElementHandles', function () {
@ -341,7 +341,7 @@ describe('Query handler tests', function () {
const elementHandle = (await page.$('div'))!;
expect(await elementHandle.$(`xpath/span`)).toBeTruthy();
expect((await elementHandle.$$(`xpath/span`)).length).toBe(1);
expect(await elementHandle.$$(`xpath/span`)).toHaveLength(1);
});
it('should return null for non-existing element', async () => {
@ -351,7 +351,7 @@ describe('Query handler tests', function () {
const elementHandle = (await page.$('div'))!;
expect(await elementHandle.$(`xpath/span`)).toBeFalsy();
expect((await elementHandle.$$(`xpath/span`)).length).toBe(0);
expect(await elementHandle.$$(`xpath/span`)).toHaveLength(0);
});
});
});
@ -542,7 +542,7 @@ describe('Query handler tests', function () {
it('should work with selector lists', async () => {
const {page} = getTestState();
const elements = await page.$$('div, ::-p-text(world)');
expect(elements.length).toStrictEqual(3);
expect(elements).toHaveLength(3);
});
const permute = <T>(inputs: T[]): T[][] => {
@ -587,7 +587,7 @@ describe('Query handler tests', function () {
it('should not have duplicate elements from selector lists', async () => {
const {page} = getTestState();
const elements = await page.$$('::-p-text(world), button');
expect(elements.length).toStrictEqual(1);
expect(elements).toHaveLength(1);
});
});
});

View File

@ -173,7 +173,7 @@ describe('querySelector', function () {
await page.setContent('<div>A</div><br/><div>B</div>');
const elements = await page.$$('div');
expect(elements.length).toBe(2);
expect(elements).toHaveLength(2);
const promises = elements.map(element => {
return page.evaluate((e: HTMLElement) => {
return e.textContent;
@ -186,7 +186,7 @@ describe('querySelector', function () {
await page.goto(server.EMPTY_PAGE);
const elements = await page.$$('div');
expect(elements.length).toBe(0);
expect(elements).toHaveLength(0);
});
});
@ -196,8 +196,8 @@ describe('querySelector', function () {
await page.setContent('<section>test</section>');
const elements = await page.$x('/html/body/section');
expect(elements[0]!).toBeTruthy();
expect(elements.length).toBe(1);
expect(elements[0]).toBeTruthy();
expect(elements).toHaveLength(1);
});
it('should return empty array for non-existing element', async () => {
const {page} = getTestState();
@ -210,7 +210,7 @@ describe('querySelector', function () {
await page.setContent('<div></div><div></div>');
const elements = await page.$x('/html/body/div');
expect(elements.length).toBe(2);
expect(elements).toHaveLength(2);
});
});
@ -342,7 +342,7 @@ describe('querySelector', function () {
);
const html = (await page.$('html'))!;
const elements = await html.$$('div');
expect(elements.length).toBe(2);
expect(elements).toHaveLength(2);
const promises = elements.map(element => {
return page.evaluate((e: HTMLElement) => {
return e.textContent;
@ -359,7 +359,7 @@ describe('querySelector', function () {
);
const html = (await page.$('html'))!;
const elements = await html.$$('div');
expect(elements.length).toBe(0);
expect(elements).toHaveLength(0);
});
});
@ -417,7 +417,7 @@ describe('querySelector', function () {
);
const html = (await page.$('html'))!;
const elements = await html.$$('allArray/div');
expect(elements.length).toBe(2);
expect(elements).toHaveLength(2);
const promises = elements.map(element => {
return page.evaluate(e => {
return e.textContent;
@ -434,7 +434,7 @@ describe('querySelector', function () {
);
const html = (await page.$('html'))!;
const elements = await html.$$('allArray/div');
expect(elements.length).toBe(0);
expect(elements).toHaveLength(0);
});
it('$$eval should work', async () => {
const {page} = getTestState();

View File

@ -30,7 +30,7 @@ import {
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
import utils from './utils.js';
import {isFavicon, waitEvent} from './utils.js';
describe('request interception', function () {
setupTestBrowserHooks();
@ -98,8 +98,8 @@ describe('request interception', function () {
}
})())!;
expect(actionResults.length).toBe(1);
expect(actionResults[0]!).toBe(expectedAction);
expect(actionResults).toHaveLength(1);
expect(actionResults[0]).toBe(expectedAction);
expect(response!.ok()).toBe(true);
});
}
@ -109,7 +109,7 @@ describe('request interception', function () {
await page.setRequestInterception(true);
page.on('request', request => {
if (utils.isFavicon(request)) {
if (isFavicon(request)) {
request.continue({}, 0);
return;
}
@ -192,7 +192,7 @@ describe('request interception', function () {
await page.setRequestInterception(true);
const requests: HTTPRequest[] = [];
page.on('request', request => {
if (!utils.isFavicon(request)) {
if (!isFavicon(request)) {
requests.push(request);
}
request.continue({}, 0);
@ -313,11 +313,11 @@ describe('request interception', function () {
page.on('request', request => {
request.abort('internetdisconnected', 0);
});
let failedRequest!: HTTPRequest;
page.on('requestfailed', request => {
return (failedRequest = request);
});
await page.goto(server.EMPTY_PAGE).catch(() => {});
const [failedRequest] = await Promise.all([
waitEvent<HTTPRequest>(page, 'requestfailed'),
page.goto(server.EMPTY_PAGE).catch(() => {}),
]);
expect(failedRequest).toBeTruthy();
expect(failedRequest.failure()!.errorText).toBe(
'net::ERR_INTERNET_DISCONNECTED'
@ -384,11 +384,11 @@ describe('request interception', function () {
);
expect(response!.status()).toBe(200);
expect(response!.url()).toContain('empty.html');
expect(requests.length).toBe(5);
expect(requests).toHaveLength(5);
expect(requests[2]!.resourceType()).toBe('document');
// Check redirect chain
const redirectChain = response!.request().redirectChain();
expect(redirectChain.length).toBe(4);
expect(redirectChain).toHaveLength(4);
expect(redirectChain[0]!.url()).toContain('/non-existing-page.html');
expect(redirectChain[2]!.url()).toContain('/non-existing-page-3.html');
for (let i = 0; i < redirectChain.length; ++i) {
@ -404,7 +404,7 @@ describe('request interception', function () {
const requests: HTTPRequest[] = [];
page.on('request', request => {
request.continue({}, 0);
if (!utils.isFavicon(request)) {
if (!isFavicon(request)) {
requests.push(request);
}
});
@ -418,12 +418,12 @@ describe('request interception', function () {
const response = await page.goto(server.PREFIX + '/one-style.html');
expect(response!.status()).toBe(200);
expect(response!.url()).toContain('one-style.html');
expect(requests.length).toBe(5);
expect(requests).toHaveLength(5);
expect(requests[0]!.resourceType()).toBe('document');
expect(requests[1]!.resourceType()).toBe('stylesheet');
// Check redirect chain
const redirectChain = requests[1]!.redirectChain();
expect(redirectChain.length).toBe(3);
expect(redirectChain).toHaveLength(3);
expect(redirectChain[0]!.url()).toContain('/one-style.css');
expect(redirectChain[2]!.url()).toContain('/three-style.css');
});
@ -467,7 +467,7 @@ describe('request interception', function () {
let spinner = false;
// Cancel 2nd request.
page.on('request', request => {
if (utils.isFavicon(request)) {
if (isFavicon(request)) {
request.continue({}, 0);
return;
}
@ -513,7 +513,7 @@ describe('request interception', function () {
const dataURL = 'data:text/html,<div>yo</div>';
const response = await page.goto(dataURL);
expect(response!.status()).toBe(200);
expect(requests.length).toBe(1);
expect(requests).toHaveLength(1);
expect(requests[0]!.url()).toBe(dataURL);
});
it('should be able to fetch dataURL and fire dataURL requests', async () => {
@ -523,7 +523,7 @@ describe('request interception', function () {
await page.setRequestInterception(true);
const requests: HTTPRequest[] = [];
page.on('request', request => {
!utils.isFavicon(request) && requests.push(request);
!isFavicon(request) && requests.push(request);
request.continue({}, 0);
});
const dataURL = 'data:text/html,<div>yo</div>';
@ -533,7 +533,7 @@ describe('request interception', function () {
});
}, dataURL);
expect(text).toBe('<div>yo</div>');
expect(requests.length).toBe(1);
expect(requests).toHaveLength(1);
expect(requests[0]!.url()).toBe(dataURL);
});
it('should navigate to URL with hash and fire requests without hash', async () => {
@ -548,7 +548,7 @@ describe('request interception', function () {
const response = await page.goto(server.EMPTY_PAGE + '#hash');
expect(response!.status()).toBe(200);
expect(response!.url()).toBe(server.EMPTY_PAGE);
expect(requests.length).toBe(1);
expect(requests).toHaveLength(1);
expect(requests[0]!.url()).toBe(server.EMPTY_PAGE);
});
it('should work with encoded server', async () => {
@ -593,7 +593,7 @@ describe('request interception', function () {
`data:text/html,<link rel="stylesheet" href="${server.PREFIX}/fonts?helvetica|arial"/>`
);
expect(response!.status()).toBe(200);
expect(requests.length).toBe(2);
expect(requests).toHaveLength(2);
expect(requests[1]!.response()!.status()).toBe(404);
});
it('should not throw "Invalid Interception Id" if the request was cancelled', async () => {
@ -613,7 +613,7 @@ describe('request interception', function () {
server.EMPTY_PAGE
),
// Wait for request interception.
await utils.waitEvent(page, 'request');
await waitEvent(page, 'request');
// Delete frame to cause request to be canceled.
await page.$eval('iframe', frame => {
return frame.remove();
@ -666,13 +666,13 @@ describe('request interception', function () {
return request.continue({}, 0);
});
const cached = [];
const cached: HTTPRequest[] = [];
page.on('requestservedfromcache', r => {
return cached.push(r);
});
await page.reload();
expect(cached.length).toBe(0);
expect(cached).toHaveLength(0);
});
it('should cache if cache enabled', async () => {
const {page, server} = getTestState();
@ -686,13 +686,13 @@ describe('request interception', function () {
return request.continue({}, 0);
});
const cached = [];
const cached: HTTPRequest[] = [];
page.on('requestservedfromcache', r => {
return cached.push(r);
});
await page.reload();
expect(cached.length).toBe(1);
expect(cached).toHaveLength(1);
});
it('should load fonts if cache enabled', async () => {
const {page, server} = getTestState();
@ -748,11 +748,11 @@ describe('request interception', function () {
: undefined;
request.continue({url: redirectURL}, 0);
});
let consoleMessage!: ConsoleMessage;
page.on('console', msg => {
return (consoleMessage = msg);
});
await page.goto(server.EMPTY_PAGE);
const [consoleMessage] = await Promise.all([
waitEvent<ConsoleMessage>(page, 'console'),
page.goto(server.EMPTY_PAGE),
]);
expect(page.url()).toBe(server.EMPTY_PAGE);
expect(consoleMessage.text()).toBe('yellow');
});
@ -895,7 +895,7 @@ describe('request interception', function () {
);
});
const response = await page.goto(server.PREFIX + '/rrredirect');
expect(response!.request().redirectChain().length).toBe(1);
expect(response!.request().redirectChain()).toHaveLength(1);
expect(response!.request().redirectChain()[0]!.url()).toBe(
server.PREFIX + '/rrredirect'
);

View File

@ -26,7 +26,7 @@ import {
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
import utils from './utils.js';
import {isFavicon, waitEvent} from './utils.js';
describe('request interception', function () {
setupTestBrowserHooks();
@ -37,7 +37,7 @@ describe('request interception', function () {
await page.setRequestInterception(true);
page.on('request', request => {
if (utils.isFavicon(request)) {
if (isFavicon(request)) {
request.continue();
return;
}
@ -118,7 +118,7 @@ describe('request interception', function () {
await page.setRequestInterception(true);
const requests: HTTPRequest[] = [];
page.on('request', request => {
if (!utils.isFavicon(request)) {
if (!isFavicon(request)) {
requests.push(request);
}
request.continue();
@ -240,11 +240,11 @@ describe('request interception', function () {
page.on('request', request => {
request.abort('internetdisconnected');
});
let failedRequest!: HTTPRequest;
page.on('requestfailed', request => {
return (failedRequest = request);
});
await page.goto(server.EMPTY_PAGE).catch(() => {});
const [failedRequest] = await Promise.all([
waitEvent<HTTPRequest>(page, 'requestfailed'),
page.goto(server.EMPTY_PAGE).catch(() => {}),
]);
expect(failedRequest).toBeTruthy();
expect(failedRequest.failure()!.errorText).toBe(
'net::ERR_INTERNET_DISCONNECTED'
@ -311,11 +311,11 @@ describe('request interception', function () {
))!;
expect(response.status()).toBe(200);
expect(response.url()).toContain('empty.html');
expect(requests.length).toBe(5);
expect(requests).toHaveLength(5);
expect(requests[2]!.resourceType()).toBe('document');
// Check redirect chain
const redirectChain = response.request().redirectChain();
expect(redirectChain.length).toBe(4);
expect(redirectChain).toHaveLength(4);
expect(redirectChain[0]!.url()).toContain('/non-existing-page.html');
expect(redirectChain[2]!.url()).toContain('/non-existing-page-3.html');
for (let i = 0; i < redirectChain.length; ++i) {
@ -331,7 +331,7 @@ describe('request interception', function () {
const requests: HTTPRequest[] = [];
page.on('request', request => {
request.continue();
if (!utils.isFavicon(request)) {
if (!isFavicon(request)) {
requests.push(request);
}
});
@ -345,12 +345,12 @@ describe('request interception', function () {
const response = (await page.goto(server.PREFIX + '/one-style.html'))!;
expect(response.status()).toBe(200);
expect(response.url()).toContain('one-style.html');
expect(requests.length).toBe(5);
expect(requests).toHaveLength(5);
expect(requests[0]!.resourceType()).toBe('document');
expect(requests[1]!.resourceType()).toBe('stylesheet');
// Check redirect chain
const redirectChain = requests[1]!.redirectChain();
expect(redirectChain.length).toBe(3);
expect(redirectChain).toHaveLength(3);
expect(redirectChain[0]!.url()).toContain('/one-style.css');
expect(redirectChain[2]!.url()).toContain('/three-style.css');
});
@ -394,7 +394,7 @@ describe('request interception', function () {
let spinner = false;
// Cancel 2nd request.
page.on('request', request => {
if (utils.isFavicon(request)) {
if (isFavicon(request)) {
request.continue();
return;
}
@ -440,7 +440,7 @@ describe('request interception', function () {
const dataURL = 'data:text/html,<div>yo</div>';
const response = (await page.goto(dataURL))!;
expect(response.status()).toBe(200);
expect(requests.length).toBe(1);
expect(requests).toHaveLength(1);
expect(requests[0]!.url()).toBe(dataURL);
});
it('should be able to fetch dataURL and fire dataURL requests', async () => {
@ -450,7 +450,7 @@ describe('request interception', function () {
await page.setRequestInterception(true);
const requests: HTTPRequest[] = [];
page.on('request', request => {
!utils.isFavicon(request) && requests.push(request);
!isFavicon(request) && requests.push(request);
request.continue();
});
const dataURL = 'data:text/html,<div>yo</div>';
@ -460,7 +460,7 @@ describe('request interception', function () {
});
}, dataURL);
expect(text).toBe('<div>yo</div>');
expect(requests.length).toBe(1);
expect(requests).toHaveLength(1);
expect(requests[0]!.url()).toBe(dataURL);
});
it('should navigate to URL with hash and fire requests without hash', async () => {
@ -475,7 +475,7 @@ describe('request interception', function () {
const response = (await page.goto(server.EMPTY_PAGE + '#hash'))!;
expect(response.status()).toBe(200);
expect(response.url()).toBe(server.EMPTY_PAGE);
expect(requests.length).toBe(1);
expect(requests).toHaveLength(1);
expect(requests[0]!.url()).toBe(server.EMPTY_PAGE);
});
it('should work with encoded server', async () => {
@ -522,7 +522,7 @@ describe('request interception', function () {
`data:text/html,<link rel="stylesheet" href="${server.PREFIX}/fonts?helvetica|arial"/>`
))!;
expect(response.status()).toBe(200);
expect(requests.length).toBe(2);
expect(requests).toHaveLength(2);
expect(requests[1]!.response()!.status()).toBe(404);
});
it('should not throw "Invalid Interception Id" if the request was cancelled', async () => {
@ -542,7 +542,7 @@ describe('request interception', function () {
server.EMPTY_PAGE
),
// Wait for request interception.
await utils.waitEvent(page, 'request');
await waitEvent(page, 'request');
// Delete frame to cause request to be canceled.
await page.$eval('iframe', frame => {
return frame.remove();
@ -595,13 +595,13 @@ describe('request interception', function () {
return request.continue();
});
const cached = [];
const cached: HTTPRequest[] = [];
page.on('requestservedfromcache', r => {
return cached.push(r);
});
await page.reload();
expect(cached.length).toBe(0);
expect(cached).toHaveLength(0);
});
it('should cache if cache enabled', async () => {
const {page, server} = getTestState();
@ -615,13 +615,13 @@ describe('request interception', function () {
return request.continue();
});
const cached = [];
const cached: HTTPRequest[] = [];
page.on('requestservedfromcache', r => {
return cached.push(r);
});
await page.reload();
expect(cached.length).toBe(1);
expect(cached).toHaveLength(1);
});
it('should load fonts if cache enabled', async () => {
const {page, server} = getTestState();
@ -678,11 +678,10 @@ describe('request interception', function () {
: undefined;
request.continue({url: redirectURL});
});
let consoleMessage!: ConsoleMessage;
page.on('console', msg => {
return (consoleMessage = msg);
});
await page.goto(server.EMPTY_PAGE);
const [consoleMessage] = await Promise.all([
waitEvent<ConsoleMessage>(page, 'console'),
page.goto(server.EMPTY_PAGE),
]);
expect(page.url()).toBe(server.EMPTY_PAGE);
expect(consoleMessage.text()).toBe('yellow');
});
@ -815,7 +814,7 @@ describe('request interception', function () {
});
});
const response = (await page.goto(server.PREFIX + '/rrredirect'))!;
expect(response.request().redirectChain().length).toBe(1);
expect(response.request().redirectChain()).toHaveLength(1);
expect(response.request().redirectChain()[0]!.url()).toBe(
server.PREFIX + '/rrredirect'
);

View File

@ -99,7 +99,7 @@ describe('Screenshots', function () {
);
}
const screenshots = await Promise.all(promises);
expect(screenshots[1]!).toBeGolden('grid-cell-1.png');
expect(screenshots[1]).toBeGolden('grid-cell-1.png');
});
it('should take fullPage screenshots', async () => {
const {page, server} = getTestState();
@ -193,11 +193,7 @@ describe('Screenshots', function () {
const screenshot = await page.screenshot({
encoding: 'base64',
});
// TODO (@jackfranklin): improve the screenshot types.
// - if we pass encoding: 'base64', it returns a string
// - else it returns a buffer.
// If we can fix that we can avoid this "as string" here.
expect(Buffer.from(screenshot as string, 'base64')).toBeGolden(
expect(Buffer.from(screenshot, 'base64')).toBeGolden(
'screenshot-sanity.png'
);
});

View File

@ -26,9 +26,7 @@ import {
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
import utils from './utils.js';
const {waitEvent} = utils;
import {waitEvent} from './utils.js';
describe('Target', function () {
setupTestBrowserHooks();
@ -55,7 +53,7 @@ describe('Target', function () {
// The pages will be the testing page
const allPages = await context.pages();
expect(allPages.length).toBe(1);
expect(allPages).toHaveLength(1);
expect(allPages).toContain(page);
});
it('should contain browser target', async () => {
@ -131,13 +129,11 @@ describe('Target', function () {
expect(allPages).toContain(page);
expect(allPages).toContain(otherPage);
const closePagePromise = new Promise(fulfill => {
return context.once('targetdestroyed', target => {
return fulfill(target.page());
});
});
await otherPage!.close();
expect(await closePagePromise).toBe(otherPage);
const [closedTarget] = await Promise.all([
waitEvent<Target>(context, 'targetdestroyed'),
otherPage!.close(),
]);
expect(await closedTarget.page()).toBe(otherPage);
allPages = (await Promise.all(
context.targets().map(target => {
@ -151,11 +147,7 @@ describe('Target', function () {
const {page, server, context} = getTestState();
await page.goto(server.EMPTY_PAGE);
const createdTarget = new Promise<Target>(fulfill => {
return context.once('targetcreated', target => {
return fulfill(target);
});
});
const createdTarget = waitEvent(context, 'targetcreated');
await page.goto(server.PREFIX + '/serviceworkers/empty/sw.html');
@ -164,11 +156,7 @@ describe('Target', function () {
server.PREFIX + '/serviceworkers/empty/sw.js'
);
const destroyedTarget = new Promise(fulfill => {
return context.once('targetdestroyed', target => {
return fulfill(target);
});
});
const destroyedTarget = waitEvent(context, 'targetdestroyed');
await page.evaluate(() => {
return (
globalThis as unknown as {
@ -216,19 +204,11 @@ describe('Target', function () {
const {page, server, context} = getTestState();
await page.goto(server.EMPTY_PAGE);
let changedTarget = new Promise<Target>(fulfill => {
return context.once('targetchanged', target => {
return fulfill(target);
});
});
let changedTarget = waitEvent(context, 'targetchanged');
await page.goto(server.CROSS_PROCESS_PREFIX + '/');
expect((await changedTarget).url()).toBe(server.CROSS_PROCESS_PREFIX + '/');
changedTarget = new Promise(fulfill => {
return context.once('targetchanged', target => {
return fulfill(target);
});
});
changedTarget = waitEvent(context, 'targetchanged');
await page.goto(server.EMPTY_PAGE);
expect((await changedTarget).url()).toBe(server.EMPTY_PAGE);
});
@ -240,21 +220,13 @@ describe('Target', function () {
return (targetChanged = true);
};
context.on('targetchanged', listener);
const targetPromise = new Promise<Target>(fulfill => {
return context.once('targetcreated', target => {
return fulfill(target);
});
});
const targetPromise = waitEvent<Target>(context, 'targetcreated');
const newPagePromise = context.newPage();
const target = await targetPromise;
expect(target.url()).toBe('about:blank');
const newPage = await newPagePromise;
const targetPromise2 = new Promise<Target>(fulfill => {
return context.once('targetcreated', target => {
return fulfill(target);
});
});
const targetPromise2 = waitEvent<Target>(context, 'targetcreated');
const evaluatePromise = newPage.evaluate(() => {
return window.open('about:blank');
});
@ -263,7 +235,7 @@ describe('Target', function () {
await evaluatePromise;
await newPage.close();
expect(targetChanged).toBe(false);
context.removeListener('targetchanged', listener);
context.off('targetchanged', listener);
});
it('should not crash while redirecting if original request was missed', async () => {
const {page, server, context} = getTestState();
@ -297,11 +269,7 @@ describe('Target', function () {
await page.goto(server.EMPTY_PAGE);
const [createdTarget] = await Promise.all([
new Promise<Target>(fulfill => {
return context.once('targetcreated', target => {
return fulfill(target);
});
}),
waitEvent<Target>(context, 'targetcreated'),
page.goto(server.PREFIX + '/popup/window-open.html'),
]);
expect((await createdTarget.page())!.url()).toBe(

View File

@ -132,15 +132,15 @@ export const dumpFrames = (frame: Frame, indentation?: string): string[] => {
return result;
};
export const waitEvent = (
export const waitEvent = <T = any>(
emitter: EventEmitter,
eventName: string,
predicate: (event: any) => boolean = () => {
predicate: (event: T) => boolean = () => {
return true;
}
): Promise<any> => {
): Promise<T> => {
return new Promise(fulfill => {
emitter.once(eventName, (event: any) => {
emitter.on(eventName, (event: T) => {
if (!predicate(event)) {
return;
}
@ -148,17 +148,3 @@ export const waitEvent = (
});
});
};
/**
* @deprecated Use exports directly.
*/
export default {
extendExpectWithToBeGolden,
waitEvent,
dumpFrames,
navigateFrame,
isFavicon,
attachFrame,
projectRoot,
detachFrame,
};

View File

@ -32,9 +32,7 @@ describe('Workers', function () {
const {page, server} = getTestState();
await Promise.all([
new Promise(x => {
return page.once('workercreated', x);
}),
waitEvent(page, 'workercreated'),
page.goto(server.PREFIX + '/worker/worker.html'),
]);
const worker = page.workers()[0]!;
@ -47,14 +45,12 @@ describe('Workers', function () {
).toBe('worker function result');
await page.goto(server.EMPTY_PAGE);
expect(page.workers().length).toBe(0);
expect(page.workers()).toHaveLength(0);
});
it('should emit created and destroyed events', async () => {
const {page} = getTestState();
const workerCreatedPromise = new Promise<WebWorker>(x => {
return page.once('workercreated', x);
});
const workerCreatedPromise = waitEvent<WebWorker>(page, 'workercreated');
const workerObj = await page.evaluateHandle(() => {
return new Worker('data:text/javascript,1');
});
@ -62,9 +58,7 @@ describe('Workers', function () {
const workerThisObj = await worker.evaluateHandle(() => {
return this;
});
const workerDestroyedPromise = new Promise(x => {
return page.once('workerdestroyed', x);
});
const workerDestroyedPromise = waitEvent(page, 'workerdestroyed');
await page.evaluate((workerObj: Worker) => {
return workerObj.terminate();
}, workerObj);
@ -93,15 +87,13 @@ describe('Workers', function () {
it('should have JSHandles for console logs', async () => {
const {page} = getTestState();
const logPromise = new Promise<ConsoleMessage>(x => {
return page.on('console', x);
});
const logPromise = waitEvent<ConsoleMessage>(page, 'console');
await page.evaluate(() => {
return new Worker(`data:text/javascript,console.log(1,2,3,this)`);
});
const log = await logPromise;
expect(log.text()).toBe('1 2 3 JSHandle@object');
expect(log.args().length).toBe(4);
expect(log.args()).toHaveLength(4);
expect(await (await log.args()[3]!.getProperty('origin')).jsonValue()).toBe(
'null'
);
@ -109,9 +101,7 @@ describe('Workers', function () {
it('should have an execution context', async () => {
const {page} = getTestState();
const workerCreatedPromise = new Promise<WebWorker>(x => {
return page.once('workercreated', x);
});
const workerCreatedPromise = waitEvent<WebWorker>(page, 'workercreated');
await page.evaluate(() => {
return new Worker(`data:text/javascript,console.log(1)`);
});
@ -121,9 +111,7 @@ describe('Workers', function () {
it('should report errors', async () => {
const {page} = getTestState();
const errorPromise = new Promise<Error>(x => {
return page.on('pageerror', x);
});
const errorPromise = waitEvent<Error>(page, 'pageerror');
await page.evaluate(() => {
return new Worker(
`data:text/javascript, throw new Error('this is my error');`