diff --git a/docs/configuration.md b/docs/configuration.md index 1a4d84fbc..1fcbba990 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -126,6 +126,28 @@ webServer: [ The server is started as part of bootstrap, right before the `bootstrap` hook (or `bootstrapAll` for `run-workers` and `run-multiple`), and stopped after `teardown` (`teardownAll`). It starts once in the main process; workers and child processes reuse it. The interactive `shell` starts it too, `dry-run` and `check` only with `--bootstrap`. CodeceptJS stops the command and every process it spawned, including when the run is interrupted with Ctrl+C. +## Blocking Resources + +Web helpers can skip loading resources a test doesn't check. Set `blockResources` in the helper config: + +```js +helpers: { + Playwright: { + url: 'http://localhost:3000', + blockResources: ['image', 'font', 'media'], + }, +} +``` + +Allowed values are `image`, `media`, `font` and `stylesheet`. Any other value fails on startup. Matching requests are aborted before they reach the network, so tests no longer exercise those resources. + +| Helper | How it blocks | Notes | +| --- | --- | --- | +| Playwright | context route on every page, tab and session | Routing disables Playwright's HTTP cache. A `mockRoute` for a blocked URL still serves the mock. | +| Puppeteer | request interception on every page | Request interception disables Puppeteer's page cache. A `mockRoute` for a blocked URL still serves the mock. | +| CDPBrowser | CDP `Fetch` domain | Works in Chrome. Lightpanda doesn't load images in the first place. Obscura doesn't block: it ignores `Fetch.failRequest`. | +| WebDriver | WebDriver BiDi network interception, matching the request destination | Needs BiDi, which is on by default, and a browser that reports the request destination: Chrome 140 does, Chrome 131 and older don't, so nothing is blocked there. Every request makes a round trip to the test process. Ignored when BiDi is off. Appium ignores the option. | + ## Dynamic configuration A JS/TS config file is plain code, so you can read environment variables and build the config at runtime: diff --git a/docs/helpers/Kitesurf.md b/docs/helpers/Kitesurf.md index 0f6775c73..22fa8c9fb 100644 --- a/docs/helpers/Kitesurf.md +++ b/docs/helpers/Kitesurf.md @@ -85,6 +85,7 @@ Type: [object][4] * `pollInterval` **[number][8]?** interval between checks while waiting, in milliseconds. * `getPageTimeout` **[number][8]?** maximum time to wait for a page to load, in seconds. * `waitForNavigation` **[string][3]?** when a navigation is considered finished: `load`, `domcontentloaded`, or `networkidle`. +* `blockResources` **[Array][15]<[string][3]>?** resource types to skip loading: `'image'`, `'media'`, `'font'`, `'stylesheet'`. Matching requests are aborted before they reach the network. diff --git a/docs/helpers/Lightpanda.md b/docs/helpers/Lightpanda.md index 940f8125e..dce3ad986 100644 --- a/docs/helpers/Lightpanda.md +++ b/docs/helpers/Lightpanda.md @@ -102,6 +102,7 @@ Type: [object][4] * `pollInterval` **[number][8]?** interval between checks while waiting, in milliseconds. * `getPageTimeout` **[number][8]?** maximum time to wait for a page to load, in seconds. * `waitForNavigation` **[string][3]?** when a navigation is considered finished: `load`, `domcontentloaded`, or `networkidle`. +* `blockResources` **[Array][15]<[string][3]>?** resource types to skip loading: `'image'`, `'media'`, `'font'`, `'stylesheet'`. Matching requests are aborted before they reach the network. diff --git a/docs/helpers/Moli.md b/docs/helpers/Moli.md index 96fab8735..3d11562bc 100644 --- a/docs/helpers/Moli.md +++ b/docs/helpers/Moli.md @@ -91,6 +91,7 @@ Type: [object][4] * `pollInterval` **[number][8]?** interval between checks while waiting, in milliseconds. * `getPageTimeout` **[number][8]?** maximum time to wait for a page to load, in seconds. * `waitForNavigation` **[string][3]?** when a navigation is considered finished: `load`, `domcontentloaded`, or `networkidle`. +* `blockResources` **[Array][15]<[string][3]>?** resource types to skip loading: `'image'`, `'media'`, `'font'`, `'stylesheet'`. Matching requests are aborted before they reach the network. diff --git a/docs/helpers/Obscura.md b/docs/helpers/Obscura.md index bc6e29be4..0a33802c4 100644 --- a/docs/helpers/Obscura.md +++ b/docs/helpers/Obscura.md @@ -118,6 +118,7 @@ Type: [object][4] * `pollInterval` **[number][8]?** interval between checks while waiting, in milliseconds. * `getPageTimeout` **[number][8]?** maximum time to wait for a page to load, in seconds. * `waitForNavigation` **[string][3]?** when a navigation is considered finished: `load`, `domcontentloaded`, or `networkidle`. +* `blockResources` **[Array][15]<[string][3]>?** resource types to skip loading: `'image'`, `'media'`, `'font'`, `'stylesheet'`. Matching requests are aborted before they reach the network. diff --git a/docs/helpers/Playwright.md b/docs/helpers/Playwright.md index 92c869e15..e8c66d8ad 100644 --- a/docs/helpers/Playwright.md +++ b/docs/helpers/Playwright.md @@ -79,6 +79,7 @@ Type: [object][8] * `bypassCSP` **[boolean][26]?** bypass Content Security Policy or CSP * `highlightElement` **[boolean][26]?** highlight the interacting elements. Default: false. Note: only activate under verbose mode (--verbose). * `visibleLocator` **[boolean][26]?** append [`visible()`][49] to locators, so only visible elements are matched. Requires Playwright 1.63 or newer. Switch it off for a single step with `stepOpts({ visibleLocator: false })`. Not applied to `dragAndDrop`, which passes selectors to Playwright directly, nor to steps that must reach hidden elements: `grab*` methods, `scrollTo`, `seeElementInDOM`, `dontSeeElementInDOM` and `seeNumberOfElements`. When enabled, a locator matching only hidden elements fails as "element not found" instead of timing out on actionability, `strict` mode ignores hidden duplicates, and elements hidden by CSS (like a custom checkbox built on a visually hidden `input`) are no longer found. +* `blockResources` **[Array][9]<[string][7]>?** resource types to skip loading: `'image'`, `'media'`, `'font'`, `'stylesheet'`. Matching requests are aborted before they reach the network. * `instantAnimations` **[boolean][26]?** run CSS transitions, CSS animations and Web Animations 1000 times faster, so a click waits for a moving element for one frame instead of the whole animation. `transitionend` and `animationend` still fire. Chromium only. Timers and JS-driven animations keep their speed. Not applied inside cross-origin iframes that Chromium runs in a separate process. * `recordHar` **[object][8]?** record HAR and will be saved to `output/har`. See more of [HAR options][3]. * `testIdAttribute` **[string][7]?** locate elements based on the testIdAttribute. See more of [locate by test id][50]. diff --git a/docs/helpers/Puppeteer.md b/docs/helpers/Puppeteer.md index f67aa5084..8abc55a93 100644 --- a/docs/helpers/Puppeteer.md +++ b/docs/helpers/Puppeteer.md @@ -59,6 +59,7 @@ Type: [object][6] * `browser` **[string][5]?** can be changed to `firefox` when using [puppeteer-firefox][2]. * `chrome` **[object][6]?** pass additional [Puppeteer run options][31]. * `highlightElement` **[boolean][25]?** highlight the interacting elements. Default: false. Note: only activate under verbose mode (--verbose). +* `blockResources` **[Array][18]<[string][5]>?** resource types to skip loading: `'image'`, `'media'`, `'font'`, `'stylesheet'`. Matching requests are aborted before they reach the network. ## findElement diff --git a/docs/helpers/WebDriver.md b/docs/helpers/WebDriver.md index 8ecc3e2db..786de06f5 100644 --- a/docs/helpers/WebDriver.md +++ b/docs/helpers/WebDriver.md @@ -32,6 +32,7 @@ Type: [object][19] * `url` **[string][18]** base url of website to be tested. * `browser` **[string][18]** Browser in which to perform testing. * `bidiProtocol` **[boolean][34]?** WebDriver Bidi Protocol. Default: false. More info: [https://webdriver.io/docs/api/webdriverBidi/][38] +* `blockResources` **[Array][30]<[string][18]>?** resource types to skip loading: `'image'`, `'media'`, `'font'`, `'stylesheet'`. Matching requests are aborted before they reach the network. * `basicAuth` **[string][18]?** (optional) the basic authentication to pass to base url. Example: {username: 'username', password: 'password'} * `host` **[string][18]?** WebDriver host to connect. * `port` **[number][23]?** WebDriver port to connect. diff --git a/lib/helper/Appium.js b/lib/helper/Appium.js index ac375c57c..4b446a83a 100644 --- a/lib/helper/Appium.js +++ b/lib/helper/Appium.js @@ -314,6 +314,8 @@ class Appium extends Webdriver { ] } + async _blockResources() {} + async _startBrowser() { if (this.appiumV2 === true) { this.options.capabilities = this._convertAppiumV2Caps(this.options.capabilities) diff --git a/lib/helper/CDPBrowser.js b/lib/helper/CDPBrowser.js index 8c1239c43..38ea83e98 100644 --- a/lib/helper/CDPBrowser.js +++ b/lib/helper/CDPBrowser.js @@ -13,7 +13,7 @@ import { ariaSnapshotFromAXNodes } from '../aria.js' import Locator from '../locator.js' import output from '../output.js' import store from '../store.js' -import { xpathLocator, normalizePath, resolveUrl, toCamelCase, convertCssPropertiesToCamelCase, normalizeSpacesInString, fileExists, base64EncodeFile, getMimeType, isFile, isWindows, screenshotOutputFolder } from '../utils.js' +import { ucfirst, xpathLocator, normalizePath, resolveUrl, toCamelCase, convertCssPropertiesToCamelCase, normalizeSpacesInString, fileExists, base64EncodeFile, getMimeType, isFile, isWindows, screenshotOutputFolder } from '../utils.js' import ElementNotFound from './errors/ElementNotFound.js' import MultipleElementsFound from './errors/MultipleElementsFound.js' import { includes as stringIncludes } from '../assert/include.js' @@ -25,7 +25,7 @@ import WebElement from '../element/WebElement.js' import CDPElementHandle from './extras/CDPElementHandle.js' import { checkFocusBeforeType, checkFocusBeforePressKey } from './extras/focusCheck.js' import { CLIPBOARD_READ_TIMEOUT_MS, readClipboardScript, writeClipboardScript, clipboardExpression } from './extras/clipboard.js' -import { dontSeeTraffic, seeTraffic, grabRecordedNetworkTraffics, flushNetworkTraffics } from './network/actions.js' +import { dontSeeTraffic, seeTraffic, grabRecordedNetworkTraffics, flushNetworkTraffics, validateBlockResources } from './network/actions.js' import { assembleApng, isPng } from './extras/apngAssembler.js' /** @@ -46,6 +46,7 @@ import { assembleApng, isPng } from './extras/apngAssembler.js' * @prop {number} [pollInterval=25] - interval between checks while waiting, in milliseconds. * @prop {number} [getPageTimeout=30] - maximum time to wait for a page to load, in seconds. * @prop {string} [waitForNavigation=load] - when a navigation is considered finished: `load`, `domcontentloaded`, or `networkidle`. + * @prop {string[]} [blockResources] - resource types to skip loading: `'image'`, `'media'`, `'font'`, `'stylesheet'`. Matching requests are aborted before they reach the network. */ const config = {} @@ -128,8 +129,10 @@ class CDPBrowser extends Helper { pollInterval: 25, getPageTimeout: 30, waitForNavigation: 'load', + blockResources: [], ...config, } + validateBlockResources(this.options.blockResources) this.cdp = null this.sessionId = null this.targetId = null @@ -360,6 +363,13 @@ class CDPBrowser extends Helper { const endpoint = await this._resolveEndpoint() this.cdp = new CDPConnection(endpoint, { headers: this.options.headers, timeout: this.options.getPageTimeout * 1000 }) await this.cdp.connect() + this.cdp.on('Fetch.requestPaused', (params, sessionId) => { + if (this.options.blockResources.includes(params.resourceType.toLowerCase())) { + this.cdp.send('Fetch.failRequest', { requestId: params.requestId, errorReason: 'BlockedByClient' }, sessionId).catch(err => this.debugSection('blockResources', err.message)) + return + } + this.cdp.send('Fetch.continueRequest', { requestId: params.requestId }, sessionId).catch(err => this.debugSection('blockResources', err.message)) + }) } _beforeStep() { @@ -385,6 +395,9 @@ class CDPBrowser extends Helper { await this.cdp.send('Page.enable', {}, this.sessionId).catch(() => null) await this.cdp.send('Runtime.enable', {}, this.sessionId).catch(() => null) await this.cdp.send('Page.setLifecycleEventsEnabled', { enabled: true }, this.sessionId).catch(() => null) + if (this.options.blockResources.length) { + await this.cdp.send('Fetch.enable', { patterns: this.options.blockResources.map(type => ({ urlPattern: '*', resourceType: ucfirst(type) })) }, this.sessionId) + } await this._probeCapabilities() } diff --git a/lib/helper/Playwright.js b/lib/helper/Playwright.js index 1dbf69b14..84b3eecc3 100644 --- a/lib/helper/Playwright.js +++ b/lib/helper/Playwright.js @@ -60,7 +60,7 @@ const checkableRoles = ['checkbox', 'radio', 'switch'] import { setRestartStrategy, restartsSession, restartsContext, restartsBrowser } from './extras/PlaywrightRestartOpts.js' import { createValueEngine, createDisabledEngine } from './extras/PlaywrightPropEngine.js' import { seeElementError, dontSeeElementError, dontSeeElementInDOMError, seeElementInDOMError } from './errors/ElementAssertion.js' -import { dontSeeTraffic, seeTraffic, grabRecordedNetworkTraffics, stopRecordingTraffic, flushNetworkTraffics } from './network/actions.js' +import { dontSeeTraffic, seeTraffic, grabRecordedNetworkTraffics, stopRecordingTraffic, flushNetworkTraffics, validateBlockResources } from './network/actions.js' const pathSeparator = path.sep @@ -108,6 +108,7 @@ const pathSeparator = path.sep * @prop {boolean} [bypassCSP] - bypass Content Security Policy or CSP * @prop {boolean} [highlightElement] - highlight the interacting elements. Default: false. Note: only activate under verbose mode (--verbose). * @prop {boolean} [visibleLocator=false] - append [`visible()`](https://playwright.dev/docs/api/class-locator#locator-visible) to locators, so only visible elements are matched. Requires Playwright 1.63 or newer. Switch it off for a single step with `stepOpts({ visibleLocator: false })`. Not applied to `dragAndDrop`, which passes selectors to Playwright directly, nor to steps that must reach hidden elements: `grab*` methods, `scrollTo`, `seeElementInDOM`, `dontSeeElementInDOM` and `seeNumberOfElements`. When enabled, a locator matching only hidden elements fails as "element not found" instead of timing out on actionability, `strict` mode ignores hidden duplicates, and elements hidden by CSS (like a custom checkbox built on a visually hidden `input`) are no longer found. + * @prop {string[]} [blockResources] - resource types to skip loading: `'image'`, `'media'`, `'font'`, `'stylesheet'`. Matching requests are aborted before they reach the network. * @prop {boolean} [instantAnimations=false] - run CSS transitions, CSS animations and Web Animations 1000 times faster, so a click waits for a moving element for one frame instead of the whole animation. `transitionend` and `animationend` still fire. Chromium only. Timers and JS-driven animations keep their speed. Not applied inside cross-origin iframes that Chromium runs in a separate process. * @prop {object} [recordHar] - record HAR and will be saved to `output/har`. See more of [HAR options](https://playwright.dev/docs/api/class-browser#browser-new-context-option-record-har). * @prop {string} [testIdAttribute=data-testid] - locate elements based on the testIdAttribute. See more of [locate by test id](https://playwright.dev/docs/locators#locate-by-test-id). @@ -421,6 +422,7 @@ class Playwright extends Helper { onResponse: null, strict: false, visibleLocator: false, + blockResources: [], instantAnimations: false, } @@ -431,6 +433,8 @@ class Playwright extends Helper { throw new Error(`Invalid config. Can't use browser "${config.browser}". Accepted values: ${availableBrowsers.join(', ')}`) } + validateBlockResources(config.blockResources) + return config } @@ -1263,6 +1267,12 @@ class Playwright extends Helper { } async _setupContext(context) { + if (this.options.blockResources.length) { + await context.route(() => true, route => { + if (this.options.blockResources.includes(route.request().resourceType())) return route.abort('blockedbyclient') + return route.fallback() + }) + } if (!this.options.instantAnimations) return if (this.options.browser !== 'chromium') { this.debugSection('instantAnimations', 'supported in Chromium only, ignored') diff --git a/lib/helper/Puppeteer.js b/lib/helper/Puppeteer.js index 64099880a..603b2297a 100644 --- a/lib/helper/Puppeteer.js +++ b/lib/helper/Puppeteer.js @@ -47,7 +47,7 @@ import { blurElement } from './scripts/blurElement.js' import { dropFile } from './scripts/dropFile.js' import { waitForChange } from './scripts/waitForChange.js' import { dontSeeElementError, seeElementError, dontSeeElementInDOMError, seeElementInDOMError } from './errors/ElementAssertion.js' -import { dontSeeTraffic, seeTraffic, grabRecordedNetworkTraffics, stopRecordingTraffic, flushNetworkTraffics } from './network/actions.js' +import { dontSeeTraffic, seeTraffic, grabRecordedNetworkTraffics, stopRecordingTraffic, flushNetworkTraffics, validateBlockResources } from './network/actions.js' import WebElement from '../element/WebElement.js' import { selectElement } from './extras/elementSelection.js' import { fillRichEditor } from './extras/richTextEditor.js' @@ -99,6 +99,7 @@ const consoleLogStore = new Console() * @prop {string} [browser=chrome] - can be changed to `firefox` when using [puppeteer-firefox](https://codecept.io/helpers/puppeteer-firefox). * @prop {object} [chrome] - pass additional [Puppeteer run options](https://github.com/puppeteer/puppeteer/blob/main/docs/api/puppeteer.launchoptions.md). * @prop {boolean} [highlightElement] - highlight the interacting elements. Default: false. Note: only activate under verbose mode (--verbose). + * @prop {string[]} [blockResources] - resource types to skip loading: `'image'`, `'media'`, `'font'`, `'stylesheet'`. Matching requests are aborted before they reach the network. */ const config = {} @@ -284,9 +285,12 @@ class Puppeteer extends Helper { defaultPopupAction: 'accept', highlightElement: false, strict: false, + blockResources: [], } - return Object.assign(defaults, config) + config = Object.assign(defaults, config) + validateBlockResources(config.blockResources) + return config } _getOptions(config) { @@ -577,6 +581,16 @@ class Puppeteer extends Helper { stringIncludes('text in popup').assert(text, popupText) } + async _blockResources(page) { + if (!this.options.blockResources.length) return + await page.setRequestInterception(true) + page.on('request', request => { + if (request.isInterceptResolutionHandled()) return + if (this.options.blockResources.includes(request.resourceType())) return request.abort('blockedbyclient', 0) + return request.continue(request.continueRequestOverrides(), 0) + }) + } + /** * Set current page * @param {object} page page to set @@ -712,7 +726,7 @@ class Puppeteer extends Helper { if (existingPages.length) { // Run the handler as it will not be triggered if the page already exists - targetCreatedHandler.call(this, mainPage) + await targetCreatedHandler.call(this, mainPage) } await this._setPage(mainPage) await this.closeOtherTabs() @@ -2948,7 +2962,7 @@ class Puppeteer extends Helper { // @ts-ignore handler(interceptedRequest) } else { - interceptedRequest.continue() + interceptedRequest.continue(interceptedRequest.continueRequestOverrides(), 0) } }) } @@ -2968,13 +2982,8 @@ class Puppeteer extends Helper { this.page.off('request') // Resume normal request handling for the given URL - this.page.on('request', interceptedRequest => { - if (interceptedRequest.url().includes(url)) { - interceptedRequest.continue() - } else { - interceptedRequest.continue() - } - }) + this.page.on('request', interceptedRequest => interceptedRequest.continue(interceptedRequest.continueRequestOverrides(), 0)) + await this._blockResources(this.page) } /** @@ -2992,6 +3001,7 @@ class Puppeteer extends Helper { async stopRecordingTraffic() { await this.page.setRequestInterception(false) stopRecordingTraffic.call(this) + await this._blockResources(this.page) } /** @@ -3019,7 +3029,7 @@ class Puppeteer extends Helper { if (typeof information.requestPostData === 'object') { information.requestPostData = JSON.parse(information.requestPostData) } - request.continue() + request.continue(request.continueRequestOverrides(), 0) this.requests.push(information) }) } @@ -3627,6 +3637,7 @@ async function targetCreatedHandler(page) { const height = parseInt(dimensions[1], 10) await page.setViewport({ width, height }) } + await this._blockResources(page) } // BC compatibility for Puppeteer < 10 diff --git a/lib/helper/WebDriver.js b/lib/helper/WebDriver.js index 09a7b9821..87909ffe6 100644 --- a/lib/helper/WebDriver.js +++ b/lib/helper/WebDriver.js @@ -42,7 +42,7 @@ import { blurElement } from './scripts/blurElement.js' import { dontSeeElementError, seeElementError, seeElementInDOMError, dontSeeElementInDOMError } from './errors/ElementAssertion.js' import { dropFile } from './scripts/dropFile.js' import { waitForChange } from './scripts/waitForChange.js' -import { dontSeeTraffic, seeTraffic, grabRecordedNetworkTraffics, stopRecordingTraffic, flushNetworkTraffics } from './network/actions.js' +import { dontSeeTraffic, seeTraffic, grabRecordedNetworkTraffics, stopRecordingTraffic, flushNetworkTraffics, validateBlockResources } from './network/actions.js' import WebElement from '../element/WebElement.js' import { selectElement } from './extras/elementSelection.js' import Downloads from './extras/Download.js' @@ -75,6 +75,7 @@ function wrapError(e) { * @prop {string} url - base url of website to be tested. * @prop {string} browser - Browser in which to perform testing. * @prop {boolean} [bidiProtocol=false] - WebDriver Bidi Protocol. Default: false. More info: https://webdriver.io/docs/api/webdriverBidi/ + * @prop {string[]} [blockResources] - resource types to skip loading: `'image'`, `'media'`, `'font'`, `'stylesheet'`. Matching requests are aborted before they reach the network. * @prop {string} [basicAuth] - (optional) the basic authentication to pass to base url. Example: {username: 'username', password: 'password'} * @prop {string} [host=localhost] - WebDriver host to connect. * @prop {number} [port=4444] - WebDriver port to connect. @@ -512,10 +513,12 @@ class WebDriver extends Helper { deprecationWarnings: false, highlightElement: false, strict: false, + blockResources: [], } // override defaults with config config = Object.assign(defaults, config) + validateBlockResources(config.blockResources) if (config.host) { // webdriverio spec @@ -691,9 +694,30 @@ class WebDriver extends Helper { }) } + await this._blockResources(this.browser) + return this.browser } + async _blockResources(browser) { + if (!this.options.blockResources.length) return + if (!browser.capabilities.webSocketUrl) { + this.debugSection('blockResources', 'requires WebDriver BiDi, ignored') + return + } + const destinations = { image: ['image'], media: ['audio', 'video', 'track'], font: ['font'], stylesheet: ['style'] } + const blocked = this.options.blockResources.flatMap(type => destinations[type]) + await browser.sessionSubscribe({ events: ['network.beforeRequestSent'] }) + const { intercept } = await browser.networkAddIntercept({ phases: ['beforeRequestSent'] }) + browser.on('network.beforeRequestSent', params => { + if (!params.isBlocked || !params.intercepts.includes(intercept)) return + if (blocked.includes(params.request.destination)) { + return browser.networkFailRequest({ request: params.request.request }).catch(err => this.debugSection('blockResources', err.message)) + } + return browser.networkContinueRequest({ request: params.request.request }).catch(err => this.debugSection('blockResources', err.message)) + }) + } + _isCustomLocatorStrategyDefined() { return this.customLocatorStrategies && Object.keys(this.customLocatorStrategies).length } @@ -748,6 +772,7 @@ class WebDriver extends Helper { opts = this._validateConfig(Object.assign(this.options, opts)) this.debugSection('New Browser', JSON.stringify(opts)) const browser = await webdriverio.remote(opts) + await this._blockResources(browser) this.activeSessionName = sessionName if (opts.timeouts && this.isWeb) { await this._defineBrowserTimeout(browser, opts.timeouts) diff --git a/lib/helper/network/actions.js b/lib/helper/network/actions.js index 34d287833..7430ca34d 100644 --- a/lib/helper/network/actions.js +++ b/lib/helper/network/actions.js @@ -124,4 +124,12 @@ function flushNetworkTraffics() { this.requests = [] } -export { dontSeeTraffic, seeTraffic, grabRecordedNetworkTraffics, stopRecordingTraffic, flushNetworkTraffics } +function validateBlockResources(blockResources) { + for (const type of blockResources) { + if (!['image', 'media', 'font', 'stylesheet'].includes(type)) { + throw new Error(`Invalid config. Can't block resource type "${type}". Accepted values: image, media, font, stylesheet`) + } + } +} + +export { dontSeeTraffic, seeTraffic, grabRecordedNetworkTraffics, stopRecordingTraffic, flushNetworkTraffics, validateBlockResources } diff --git a/test/helper/webapi.js b/test/helper/webapi.js index c423ec928..1a70181dd 100644 --- a/test/helper/webapi.js +++ b/test/helper/webapi.js @@ -2771,6 +2771,61 @@ export function tests() { }) }) + describe('#blockResources', () => { + const logo = /codeceptjs\.png$/ + + beforeEach(async () => { + await I._after() + I.options.blockResources = ['image'] + await I._before() + }) + + afterEach(async () => { + await I._after() + I.options.blockResources = [] + await I._before() + }) + + it('should not load blocked resource types', async function () { + if (isHelper('Lightpanda')) this.skip() // Lightpanda never fetches images (verified: naturalWidth is 0 with no blocking), so blocking can't be observed + if (isHelper('WebDriver') && parseInt(I.browser.capabilities.browserVersion, 10) < 140) this.skip() // Chrome's BiDi before 140 sends no request.destination, so the resource type can't be matched (verified: Chrome 130 and 131 omit it, Chrome 140 sends 'image') + if (isHelper('Obscura')) this.skip() // Obscura emits Fetch.requestPaused for every request, ignoring resourceType patterns, and Fetch.failRequest doesn't stop the load (verified: the image still loads with naturalWidth 333) + await I.amOnPage('/image') + await I.waitForFunction(() => document.getElementById('logo').complete, 5) + const width = await I.executeScript(() => document.getElementById('logo').naturalWidth) + assert.equal(width, 0) + }) + + it('should serve a blocked resource mocked with mockRoute', async function () { + if (!I.mockRoute) this.skip() + const png = path.join(__dirname, '/../data/app/codeceptjs.png') + if (isHelper('Puppeteer')) { + await I.mockRoute(logo, request => request.respond({ status: 200, contentType: 'image/png', body: fs.readFileSync(png) })) + } else { + await I.mockRoute(logo, route => route.fulfill({ path: png, contentType: 'image/png' })) + } + await I.amOnPage('/image') + await I.waitForFunction(() => document.getElementById('logo').complete, 5) + const width = await I.executeScript(() => document.getElementById('logo').naturalWidth) + assert.isAbove(width, 0) + await I.stopMockingRoute(logo) + }) + + it('should keep blocking after stopMockingRoute', async function () { + if (!I.mockRoute) this.skip() + await I.mockRoute(logo, route => route.continue()) + await I.stopMockingRoute(logo) + await I.amOnPage('/image') + await I.waitForFunction(() => document.getElementById('logo').complete, 5) + const width = await I.executeScript(() => document.getElementById('logo').naturalWidth) + assert.equal(width, 0) + }) + + it('should reject resource types that are not allowed', () => { + expect(() => new I.constructor({ url: siteUrl, browser: I.options.browser, blockResources: ['script'] })).to.throw('Accepted values: image, media, font, stylesheet') + }) + }) + describe('#startScreencast, #stopScreencast', () => { beforeEach(function () { if (typeof I.startScreencast !== 'function') this.skip() // CDP-family only (CDPBrowser/Obscura/Kitesurf) — Playwright/WebDriver/Puppeteer use their own video APIs