chore: create a test helper for launching browser (#10152)

This commit is contained in:
Nikolay Vitkov 2023-05-11 15:10:27 +02:00 committed by GitHub
parent e313b054e6
commit c00cf45009
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 73 additions and 9 deletions

View File

@ -10,4 +10,20 @@ module.exports = {
},
],
},
overrides: [
{
files: ['*.spec.ts'],
rules: {
'no-restricted-syntax': [
'warn',
{
message:
'Use helper command `launch` to make sure the browsers get cleaned',
selector:
'MemberExpression[object.name="puppeteer"][property.name="launch"]',
},
],
},
},
],
};

View File

@ -242,6 +242,10 @@ export const mochaHooks = {
],
afterEach: (): void => {
if (browserCleanups.length > 0) {
throw new Error('A manually launched browser was not closed!');
}
sinon.restore();
},
};
@ -328,3 +332,53 @@ export const createTimeout = <T>(
}, n);
});
};
const browserCleanups: Array<() => Promise<void>> = [];
export const launch = async (
options: PuppeteerLaunchOptions
): Promise<
PuppeteerTestState & {
close: () => Promise<void>;
}
> => {
const close = async () => {
let cleanup = browserCleanups.pop();
while (cleanup) {
await cleanup();
cleanup = browserCleanups.pop();
}
};
try {
const browser = await puppeteer.launch({
...defaultBrowserOptions,
...options,
});
browserCleanups.push(async () => {
browser.close();
});
const context = await browser.createIncognitoBrowserContext();
browserCleanups.push(async () => {
context.close();
});
const page = await context.newPage();
browserCleanups.push(async () => {
page.close();
});
return {
...getTestState(),
browser,
context,
page,
close,
};
} catch (error) {
await close();
throw error;
}
};

View File

@ -24,6 +24,7 @@ import {HTTPResponse} from 'puppeteer-core/internal/api/HTTPResponse.js';
import {
getTestState,
launch,
setupTestBrowserHooks,
setupTestPageAndContextHooks,
} from './mocha-utils.js';
@ -823,15 +824,9 @@ describe('network', function () {
});
it('Cross-origin set-cookie', async () => {
const {httpsServer, puppeteer, defaultBrowserOptions} = getTestState();
const browser = await puppeteer.launch({
...defaultBrowserOptions,
const {page, httpsServer, close} = await launch({
ignoreHTTPSErrors: true,
});
const page = await browser.newPage();
try {
await page.goto(httpsServer.PREFIX + '/empty.html');
@ -855,8 +850,7 @@ describe('network', function () {
]);
expect(response.headers()['set-cookie']).toBe(setCookieString);
} finally {
await page.close();
await browser.close();
await close();
}
});
});