diff --git a/README.md b/README.md index f012500..c4d16f8 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,12 @@ const await browser = launch({ ``` +## Helper Functions + +### clickAndWait(page: Page, selector: string, clickOptions?: ClickOptions, navigationOptions?: NavigationOptions) + +Clicks and waits for network request to complete and resolves. + ## Environment Variables The following environment variables are available: diff --git a/src/helpers.test.ts b/src/helpers.test.ts new file mode 100644 index 0000000..41784fe --- /dev/null +++ b/src/helpers.test.ts @@ -0,0 +1,28 @@ +import { Browser } from 'puppeteer-core' +import { clickAndWait } from './helpers' +import { launch } from './puppeteer' + +jest.setTimeout(20 * 1000) + +describe('helpers', () => { + describe(clickAndWait.name, () => { + it('should click and wait', async () => { + expect.assertions(1) + + const browser = await launch() + + try { + const page = await browser.newPage() + await page.goto('http://example.com/', { waitUntil: 'networkidle2' }) + + const res = await clickAndWait(page, 'a') + + expect(res.ok()).toBe(true) + } catch (e) { + expect(e).toBeFalsy() + } finally { + return browser.close() + } + }) + }) +}) diff --git a/src/helpers.ts b/src/helpers.ts new file mode 100644 index 0000000..76aab04 --- /dev/null +++ b/src/helpers.ts @@ -0,0 +1,21 @@ +import { Page, ClickOptions, NavigationOptions } from 'puppeteer-core' + +/** + * Clicks a link and waits for network request to complete. + */ +export async function clickAndWait( + page: Page, + selector: string, + clickOptions: ClickOptions = {}, + navigationOptions: NavigationOptions = { + waitUntil: 'networkidle2', + }, +) { + const wait = page.waitForNavigation(navigationOptions) + + const click = page.click(selector, clickOptions) + + const [response] = await Promise.all([wait, click]) + + return response +} diff --git a/src/index.test.ts b/src/index.test.ts index e3acf75..f27653b 100644 --- a/src/index.test.ts +++ b/src/index.test.ts @@ -1,8 +1,12 @@ -import { launch } from './index' +import { launch, clickAndWait } from './index' import { launch as puppeteerLaunch } from './puppeteer' describe('index', () => { it('should export our custom launch function', () => { expect(launch).toEqual(puppeteerLaunch) }) + + it(`should export ${clickAndWait.name} helper`, () => { + expect(clickAndWait).toBeTruthy() + }) }) diff --git a/src/index.ts b/src/index.ts index 912be17..4a4ccc3 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,2 +1,3 @@ export * from 'puppeteer-core' export { launch } from './puppeteer' +export * from './helpers'