From 52da8eb343d44d5d910702e99ad1c7d226cbaccc Mon Sep 17 00:00:00 2001 From: sipayrt Date: Fri, 4 Jul 2025 15:13:59 +0300 Subject: [PATCH] docs: fix test examples --- .gitignore | 1 + docs/commands/browser/assertView.mdx | 2 +- docs/commands/overview.mdx | 3 +- docs/guides/how-to-check-accessibility.mdx | 6 +- docs/guides/how-to-hide-scrollbars-by-cdp.mdx | 6 +- ...ow-to-intercept-requests-and-responses.mdx | 76 +++++++++---------- docs/guides/how-to-manage-cpu-performance.mdx | 12 +-- .../how-to-manage-network-bandwidth.mdx | 12 +-- docs/plugins/testplane-global-hook.mdx | 8 +- .../current/commands/overview.mdx | 3 +- .../guides/how-to-check-accessibility.mdx | 6 +- .../guides/how-to-hide-scrollbars-by-cdp.mdx | 6 +- ...ow-to-intercept-requests-and-responses.mdx | 76 +++++++++---------- .../guides/how-to-manage-cpu-performance.mdx | 12 +-- .../how-to-manage-network-bandwidth.mdx | 12 +-- .../current/plugins/testplane-global-hook.mdx | 46 +++++++---- 16 files changed, 155 insertions(+), 132 deletions(-) diff --git a/.gitignore b/.gitignore index 436246d..a36c167 100644 --- a/.gitignore +++ b/.gitignore @@ -16,6 +16,7 @@ .env.development.local .env.test.local .env.production.local +.vscode/ npm-debug.log* diff --git a/docs/commands/browser/assertView.mdx b/docs/commands/browser/assertView.mdx index 88b6c6a..daefc61 100644 --- a/docs/commands/browser/assertView.mdx +++ b/docs/commands/browser/assertView.mdx @@ -39,7 +39,7 @@ Required parameter. Specifies the name of the test state. The name must be uniqu ### selector -Required parameter. Specifies the selector of the DOM element to capture. If not specified or skipped, will be set to `body` and the following options will be automatically added to `options`: +Optional parameter. Specifies the selector of the DOM element to capture. If not specified or skipped, will be set to `body` and the following options will be automatically added to `options`: ``` { diff --git a/docs/commands/overview.mdx b/docs/commands/overview.mdx index fa78b15..66a145e 100644 --- a/docs/commands/overview.mdx +++ b/docs/commands/overview.mdx @@ -22,7 +22,7 @@ However, the command descriptions on the [WebDriverIO][webdriverio-api] website ```javascript it("should test something", async function () { - const browser = this.browser; + await this.browser.url("https://testplane.io"); // test code... }); ``` @@ -31,6 +31,7 @@ or get the `browser` object from the function argument (note that the `browser` ```javascript it("should test something", async ({ browser }) => { + await browser.url("https://testplane.io"); // test code... }); ``` diff --git a/docs/guides/how-to-check-accessibility.mdx b/docs/guides/how-to-check-accessibility.mdx index e543b50..c00df4a 100644 --- a/docs/guides/how-to-check-accessibility.mdx +++ b/docs/guides/how-to-check-accessibility.mdx @@ -20,14 +20,14 @@ To obtain such a tree, _puppeteer_ has a special [Accessibility class][puppeteer Here's an example of how to use it: ```javascript -it("should get accessibility tree of yandex.ru", async function () { +it("should get accessibility tree of yandex.ru", async function ({browser}) { // Get puppeteer instance - const puppeteer = await this.browser.getPuppeteer(); + const puppeteer = await browser.getPuppeteer(); // Get the first open page (considering it to be currently active) const [page] = await puppeteer.pages(); - await this.browser.url("https://yandex.ru"); + await browser.url("https://yandex.ru"); // Get the current state of the accessibility tree const snapshot = await page.accessibility.snapshot(); diff --git a/docs/guides/how-to-hide-scrollbars-by-cdp.mdx b/docs/guides/how-to-hide-scrollbars-by-cdp.mdx index 1ab4ae7..68d859f 100644 --- a/docs/guides/how-to-hide-scrollbars-by-cdp.mdx +++ b/docs/guides/how-to-hide-scrollbars-by-cdp.mdx @@ -20,9 +20,9 @@ CDP has a special method [Emulation.setScrollbarsHidden][set-scrollbars-hidden] Here's how it looks: ```javascript -it("should hide scrollbar", async function () { +it("should hide scrollbar", async function ({browser}) { // Get puppeteer instance - const puppeteer = await this.browser.getPuppeteer(); + const puppeteer = await browser.getPuppeteer(); // Get the first open page (considering it to be currently active) const [page] = await puppeteer.pages(); @@ -33,7 +33,7 @@ it("should hide scrollbar", async function () { // Hide the scrollbar await client.send("Emulation.setScrollbarsHidden", { hidden: true }); - await this.browser.url("https://yandex.ru"); + await browser.url("https://yandex.ru"); }); ``` diff --git a/docs/guides/how-to-intercept-requests-and-responses.mdx b/docs/guides/how-to-intercept-requests-and-responses.mdx index e143155..5789c29 100644 --- a/docs/guides/how-to-intercept-requests-and-responses.mdx +++ b/docs/guides/how-to-intercept-requests-and-responses.mdx @@ -30,25 +30,25 @@ Let's try writing tests using this API and cover different cases. To clarify, al ## Example 1: Mocking a Request to google.com and Returning Our Own Response {#example_1} ```javascript -it("should mock google.com", async function () { +it("should mock google.com", async function ({browser}) { // Mocking the request to google.com - const mock = await this.browser.mock("https://google.com"); + const mock = await browser.mock("https://google.com"); // Returning the string "Hello, world!" instead of the response from the site. // The "fetchResponse" option dictates whether the request should be made // to the mocked resource; default is true. mock.respond("Hello, world!", { fetchResponse: false }); - await this.browser.url("https://google.com"); + await browser.url("https://google.com"); }); ``` From the graphical representation, you can see that we returned our text, although the browser's address bar shows we navigated to _google.com._ Also, it's clear that we didn't mock the favicon, which was fetched from an external source. We can write this same example using the puppeteer API. For this, _webdriverio_ has the [getPuppeteer()][get-puppeteer] command: ```javascript -it("should mock google.com using puppeteer api", async function () { +it("should mock google.com using puppeteer api", async function ({browser}) { // Get puppeteer instance - const puppeteer = await this.browser.getPuppeteer(); + const puppeteer = await browser.getPuppeteer(); // Get the first open page (considering it to be currently active) const [page] = await puppeteer.pages(); @@ -69,7 +69,7 @@ it("should mock google.com using puppeteer api", async function () { // Here, we could call "page.goto('https://google.com')", but it's better to call "url", // because most plugins have wrappers for the "url" command adding additional logic. // For example, in testplane, the URL is added to the meta. - await this.browser.url("https://google.com"); + await browser.url("https://google.com"); }); ``` @@ -78,9 +78,9 @@ it("should mock google.com using puppeteer api", async function () { Now, let's imagine that puppeteer doesn't yet have an API for mocking requests, but this is already implemented in the [Fetch][fetch] domain of CDP. In this case, we will use this domain's method by interacting with the CDP session directly. For this, puppeteer has the [CDPSession.send()][cdp-session-send] method: ```javascript -it("should mock google.com using cdp fetch domain", async function () { +it("should mock google.com using cdp fetch domain", async function ({browser}) { // Get puppeteer instance - const puppeteer = await this.browser.getPuppeteer(); + const puppeteer = await browser.getPuppeteer(); // Get the first open page (considering it to be currently active) const [page] = await puppeteer.pages(); @@ -113,7 +113,7 @@ it("should mock google.com using cdp fetch domain", async function () { }); }); - await this.browser.url("https://google.com"); + await browser.url("https://google.com"); }); ``` @@ -122,14 +122,14 @@ Obviously, when using the _webdriverio_ API for mocking requests, the code is mu ## Example 2: Canceling the Request for Google's Logo {#example_2} ```javascript -it("should abort request to logo on google.com", async function () { +it("should abort request to logo on google.com", async function ({browser}) { // You can use a mask for the URL - const mock = await this.browser.mock("https://www.google.com/images/**/*.png"); + const mock = await browser.mock("https://www.google.com/images/**/*.png"); // Throw an error "ERR_FAILED" when loading a resource that matches the mask mock.abort("Failed"); - await this.browser.url("https://google.com"); + await browser.url("https://google.com"); }); ``` @@ -138,15 +138,15 @@ From the graphical representation, it is clear that the logo is not displayed, a ## Example 3: Loading google.com Using a Fixture for the Response {#example_3} ```javascript -it("should mock google.com and return answer from fixture", async function () { +it("should mock google.com and return answer from fixture", async function ({browser}) { // Mocking the request to google.com - const mock = await this.browser.mock("https://google.com"); + const mock = await browser.mock("https://google.com"); // Specify the path from which to take the fixture, and with // "fetchResponse: false", indicate that the real request should not be made mock.respond("./fixtures/my-google.com.html", { fetchResponse: false }); - await this.browser.url("https://google.com"); + await browser.url("https://google.com"); }); ``` @@ -155,14 +155,14 @@ From the graphical representation, it is clear that instead of google.com's cont ## Example 4: Redirecting the Request from google.com to yandex.ru {#example_4} ```javascript -it("should redirect from google.com to yandex.ru", async function () { +it("should redirect from google.com to yandex.ru", async function ({browser}) { // Mocking the request to google.com - const mock = await this.browser.mock("https://google.com"); + const mock = await browser.mock("https://google.com"); // For redirection, simply specify the URL mock.respond("https://yandex.ru"); - await this.browser.url("https://google.com"); + await browser.url("https://google.com"); }); ``` @@ -173,26 +173,26 @@ Puppeteer still does not have an API for conveniently modifying responses. There Replace all occurrences of the string `Google` with `Yandex` in google.com's response: ```javascript -it("should modify response from google.com", async function () { +it("should modify response from google.com", async function ({browser}) { // Here, you need to mock with www because navigating to google.com // returns a 301 response without a body and redirects to www - const mock = await this.browser.mock("https://www.google.com"); + const mock = await browser.mock("https://www.google.com"); mock.respond(req => { // Replace "Google" with "Yandex" using a regular expression return req.body.replace(/Google/g, "Yandex"); }); - await this.browser.url("https://google.com"); + await browser.url("https://google.com"); }); ``` Additionally, we can modify responses from unknown sources in advance. For example, let's modify all scripts loaded on _google.com:_ ```javascript -it("should modify response from google.com", async function () { +it("should modify response from google.com", async function ({browser}) { // The first argument specifies that we will intercept all requests - const mock = await this.browser.mock("**", { + const mock = await browser.mock("**", { headers: headers => { // Filter only the requests where the "content-type" // header contains values "text/javascript" or "application/javascript" @@ -208,7 +208,7 @@ it("should modify response from google.com", async function () { return (req.body += `\nconsole.log("This script was modified in real time.");`); }); - await this.browser.url("https://google.com"); + await browser.url("https://google.com"); }); ``` @@ -217,11 +217,11 @@ it("should modify response from google.com", async function () { Let's say we need to collect a list of all URLs loaded on the page. Using this information, we could determine if we have requests for external resources or neighboring services that we do not control. This means they could fail at any time and break our tests. Here's what our code might look like: ```javascript -it("should mock yandex.ru and log all loaded urls", async function () { +it("should mock yandex.ru and log all loaded urls", async function ({browser}) { // Intercept absolutely all requests - const mock = await this.browser.mock("**"); + const mock = await browser.mock("**"); - await this.browser.url("https://yandex.ru"); + await browser.url("https://yandex.ru"); // mock.calls contains not only the visited URL information // but also the response from the source, the request headers, response headers, etc. @@ -235,7 +235,7 @@ it("should mock yandex.ru and log all loaded urls", async function () { Most likely, your tests are more complex than these examples and involve various clicks on elements that open in new tabs. In such cases, the previous code will not capture the opening of new tabs or that URLs need to be collected there as well. Therefore, in such cases, you need to use puppeteer's API: ```javascript -it("should mock yandex.ru and log all loaded urls (using puppeteer)", async function () { +it("should mock yandex.ru and log all loaded urls (using puppeteer)", async function ({browser}) { // Accumulative list of all URLs const urls = []; @@ -249,7 +249,7 @@ it("should mock yandex.ru and log all loaded urls (using puppeteer)", async func } // Get puppeteer instance - const puppeteer = await this.browser.getPuppeteer(); + const puppeteer = await browser.getPuppeteer(); // Get all open pages at the current moment const pages = await puppeteer.pages(); @@ -274,10 +274,10 @@ it("should mock yandex.ru and log all loaded urls (using puppeteer)", async func urlsHandler(page); }); - await this.browser.url("https://yandex.ru"); + await browser.url("https://yandex.ru"); // Find the first element in the list of services (at that time it was a football page) - const elem = await this.browser.$(".services-new__list-item > a"); + const elem = await browser.$(".services-new__list-item > a"); // Click the service that opens in a new tab await elem.click(); @@ -298,20 +298,20 @@ module.exports = { "testplane-global-hook": { enabled: true, - beforeEach: async function () { + beforeEach: async function ({browser}) { // Check that the browser name starts with "chrome" - if (!/^chrome$/i.test(this.browser.capabilities.browserName)) { + if (!/^chrome$/i.test(browser.capabilities.browserName)) { return; } // Mocking the request to google.com - const mock = await this.browser.mock("https://google.com"); + const mock = await browser.mock("https://google.com"); mock.respond("hello world", { fetchResponse: false }); }, - afterEach: function () { + afterEach: function ({browser}) { // Clear all mocks in the current session - this.browser.mockRestoreAll(); + browser.mockRestoreAll(); }, }, @@ -327,8 +327,8 @@ The test code will now only contain the URL transition: ```javascript // Explicitly indicate that the test is only executed in browsers whose name starts with chrome testplane.only.in(/^chrome/); -it("should mock google.com inside global before each", async function () { - await this.browser.url("https://google.com"); +it("should mock google.com inside global before each", async function ({browser}) { + await browser.url("https://google.com"); }); ``` diff --git a/docs/guides/how-to-manage-cpu-performance.mdx b/docs/guides/how-to-manage-cpu-performance.mdx index 58de3aa..127a77e 100644 --- a/docs/guides/how-to-manage-cpu-performance.mdx +++ b/docs/guides/how-to-manage-cpu-performance.mdx @@ -18,9 +18,9 @@ The CPU speed on mobile devices is significantly slower than on computers. There Let's use this method to slow down CPU speed by 8 times: ```javascript -it("should open yandex.ru with emulation 8x slower CPU", async function () { +it("should open yandex.ru with emulation 8x slower CPU", async function ({browser}) { // Get puppeteer instance - const puppeteer = await this.browser.getPuppeteer(); + const puppeteer = await browser.getPuppeteer(); // Get the first open page (considering it to be currently active) const [page] = await puppeteer.pages(); @@ -28,7 +28,7 @@ it("should open yandex.ru with emulation 8x slower CPU", async function () { // Slow down the CPU speed by 8 times await page.emulateCPUThrottling(8); - await this.browser.url("https://yandex.ru"); + await browser.url("https://yandex.ru"); }); ``` @@ -39,9 +39,9 @@ Initially, _webdriverio_ did not support the `page.emulateCPUThrottling` method However, this limitation could be bypassed using puppeteer's [CDPSession.send()][cdp-session-send] method by sending the browser the [Emulation.setCPUThrottlingRate][emulation-set-cpu-throttling-rate] command via CDP: ```javascript -it("should open yandex.ru with emulation 8x slower CPU", async function () { +it("should open yandex.ru with emulation 8x slower CPU", async function ({browser}) { // Get puppeteer instance - const puppeteer = await this.browser.getPuppeteer(); + const puppeteer = await browser.getPuppeteer(); // Get the first open page (considering it to be currently active) const [page] = await puppeteer.pages(); @@ -52,7 +52,7 @@ it("should open yandex.ru with emulation 8x slower CPU", async function () { // Slow down the CPU speed by 8 times await client.send("Emulation.setCPUThrottlingRate", { rate: 8 }); - await this.browser.url("https://yandex.ru"); + await browser.url("https://yandex.ru"); }); ``` diff --git a/docs/guides/how-to-manage-network-bandwidth.mdx b/docs/guides/how-to-manage-network-bandwidth.mdx index 5ca620d..5e16f03 100644 --- a/docs/guides/how-to-manage-network-bandwidth.mdx +++ b/docs/guides/how-to-manage-network-bandwidth.mdx @@ -28,11 +28,11 @@ Besides custom settings, the [throttle][throttle] method supports the following Let's emulate a 2G connection and open yandex.ru in Chrome with phone emulation: ```javascript -it("should open yandex.ru with emulation of 2G-connection", async function () { +it("should open yandex.ru with emulation of 2G-connection", async function ({browser}) { // Emulate a 2G connection - await this.browser.throttle("Good2G"); + await browser.throttle("Good2G"); - await this.browser.url("https://yandex.ru"); + await browser.url("https://yandex.ru"); }); ``` @@ -41,16 +41,16 @@ it("should open yandex.ru with emulation of 2G-connection", async function () { We can also emulate a connection with specific characteristics: ```javascript -it("should open yandex.ru with emulation of custom connection", async function () { +it("should open yandex.ru with emulation of custom connection", async function ({browser}) { // Emulate a network connection with specified characteristics - await this.browser.throttle({ + await browser.throttle({ offline: false, // emulate offline state downloadThroughput: (10 * 1024) / 8, // max download bandwidth (byte/sec) uploadThroughput: (10 * 1024) / 8, // max upload bandwidth (byte/sec) latency: 10, // min latency from sending the request to receiving the response headers }); - await this.browser.url("https://yandex.ru"); + await browser.url("https://yandex.ru"); }); ``` diff --git a/docs/plugins/testplane-global-hook.mdx b/docs/plugins/testplane-global-hook.mdx index b4f30b7..12bb340 100644 --- a/docs/plugins/testplane-global-hook.mdx +++ b/docs/plugins/testplane-global-hook.mdx @@ -30,11 +30,11 @@ Add the plugin to the `plugins` section of the `testplane` config: module.exports = { plugins: { "testplane-global-hook": { - beforeEach: async function () { - await this.browser.deleteCookie(); // Say, we want to always clear cookies before running a test + beforeEach: async function ({browser}) { + await browser.deleteCookie(); // Say, we want to always clear cookies before running a test }, - afterEach: async function () { - await this.browser.execute(function () { + afterEach: async function ({browser}) { + await browser.execute(function () { try { localStorage.clear(); // And always clean up the localStorage after the test is completed } catch (e) {} diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/commands/overview.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/commands/overview.mdx index 1e5ceb6..6f9e209 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/commands/overview.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/commands/overview.mdx @@ -22,7 +22,7 @@ import Admonition from "@theme/Admonition"; ```javascript it("should test something", async () => { - const browser = this.browser; + await this.browser.url("https://testplane.io"); // код теста... }); ``` @@ -31,6 +31,7 @@ import Admonition from "@theme/Admonition"; ```javascript it("should test something", async ({ browser }) => { + await browser.url("https://testplane.io"); // код теста... }); ``` diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/guides/how-to-check-accessibility.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/guides/how-to-check-accessibility.mdx index 7412047..f618532 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/guides/how-to-check-accessibility.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/guides/how-to-check-accessibility.mdx @@ -20,14 +20,14 @@ import Admonition from "@theme/Admonition"; Вот пример, как его можно использовать: ```javascript -it("should get accessibility tree of yandex.ru", async function () { +it("should get accessibility tree of yandex.ru", async function ({browser}) { // Получаем инстанс puppeteer'а - const puppeteer = await this.browser.getPuppeteer(); + const puppeteer = await browser.getPuppeteer(); // Получаем первую открытую страницу (считаем, что она активная в данный момент) const [page] = await puppeteer.pages(); - await this.browser.url("https://yandex.ru"); + await browser.url("https://yandex.ru"); // Получаем текущее состояние accessibility дерева const snapshot = await page.accessibility.snapshot(); diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/guides/how-to-hide-scrollbars-by-cdp.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/guides/how-to-hide-scrollbars-by-cdp.mdx index 140f20c..36b5bc3 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/guides/how-to-hide-scrollbars-by-cdp.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/guides/how-to-hide-scrollbars-by-cdp.mdx @@ -20,9 +20,9 @@ import Admonition from "@theme/Admonition"; Вот как это будет выглядеть: ```javascript -it("should hide scrollbar", async function () { +it("should hide scrollbar", async function ({browser}) { // Получаем инстанс puppeteer'а - const puppeteer = await this.browser.getPuppeteer(); + const puppeteer = await browser.getPuppeteer(); // Получаем первую открытую страницу (считаем, что она активная в данный момент) const [page] = await puppeteer.pages(); @@ -33,7 +33,7 @@ it("should hide scrollbar", async function () { // Скрываем скроллбар await client.send("Emulation.setScrollbarsHidden", { hidden: true }); - await this.browser.url("https://yandex.ru"); + await browser.url("https://yandex.ru"); }); ``` diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/guides/how-to-intercept-requests-and-responses.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/guides/how-to-intercept-requests-and-responses.mdx index 170c1d9..27db321 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/guides/how-to-intercept-requests-and-responses.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/guides/how-to-intercept-requests-and-responses.mdx @@ -30,25 +30,25 @@ import Admonition from "@theme/Admonition"; ## Пример 1: мокаем запрос к google.com и возвращаем свой ответ {#example_1} ```javascript -it("should mock google.com", async function () { +it("should mock google.com", async function ({browser}) { // Мокаем поход на google.com - const mock = await this.browser.mock("https://google.com"); + const mock = await browser.mock("https://google.com"); // Возвращаем строку "Hello, world!" вместо ответа от сайта. // Опция "fetchResponse" отвечает за то, нужно ли делать запрос // на замоканный ресурс, по умолчанию - true mock.respond("Hello, world!", { fetchResponse: false }); - await this.browser.url("https://google.com"); + await browser.url("https://google.com"); }); ``` По графическому изображению видно, что мы вернули свой текст, при этом в строке браузера отображается как будто мы выполнили переход на _google.com._ Также видно, что мы не замокали фавиконку и она приехала снаружи. Этот же самый пример мы можем написать с использованием API puppeteer'а, для этого в _webdriverio_ реализована команда [getPuppeteer()][get-puppeteer]: ```javascript -it("should mock google.com using puppeteer api", async function () { +it("should mock google.com using puppeteer api", async function ({browser}) { // Получаем инстанс puppeteer'а - const puppeteer = await this.browser.getPuppeteer(); + const puppeteer = await browser.getPuppeteer(); // Получаем первую открытую страницу (считаем, что она активная в данный момент) const [page] = await puppeteer.pages(); @@ -69,7 +69,7 @@ it("should mock google.com using puppeteer api", async function () { // Здесь можно было бы вызвать и "page.goto('https://google.com')", но лучше вызывать "url", // так как в большинстве плагинов есть обертки команды "url", добавляющие дополнительную // логику. Например, в testplane добавляется урл в мету. - await this.browser.url("https://google.com"); + await browser.url("https://google.com"); }); ``` @@ -78,9 +78,9 @@ it("should mock google.com using puppeteer api", async function () { А теперь представим, что в _puppeteer_ еще нет API для мока запросов, но это уже реализовано в домене [Fetch][fetch] CDP. В этом случае воспользуемся методом этого домена через общение с CDP-сессией напрямую. Для этого в _puppeteer_ есть метод [CDPSession.send()][cdp-session-send]: ```javascript -it("should mock google.com using cdp fetch domain", async function () { +it("should mock google.com using cdp fetch domain", async function ({browser}) { // Получаем инстанс puppeteer'а - const puppeteer = await this.browser.getPuppeteer(); + const puppeteer = await browser.getPuppeteer(); // Получаем первую открытую страницу (считаем, что она активная в данный момент) const [page] = await puppeteer.pages(); @@ -113,7 +113,7 @@ it("should mock google.com using cdp fetch domain", async function () { }); }); - await this.browser.url("https://google.com"); + await browser.url("https://google.com"); }); ``` @@ -122,14 +122,14 @@ it("should mock google.com using cdp fetch domain", async function () { ## Пример 2: отменяем запрос за логотипом гугла {#example_2} ```javascript -it("should abort request to logo on google.com", async function () { +it("should abort request to logo on google.com", async function ({browser}) { // В качестве урла можно использовать маску - const mock = await this.browser.mock("https://www.google.com/images/**/*.png"); + const mock = await browser.mock("https://www.google.com/images/**/*.png"); // Кидаем ошибку "ERR_FAILED" при загрузке ресурса, сматчившегося на маску мока mock.abort("Failed"); - await this.browser.url("https://google.com"); + await browser.url("https://google.com"); }); ``` @@ -138,15 +138,15 @@ it("should abort request to logo on google.com", async function () { ## Пример 3: при загрузке google.com берем ответ из фикстуры {#example_3} ```javascript -it("should mock google.com and return answer from fixture", async function () { +it("should mock google.com and return answer from fixture", async function ({browser}) { // Мокаем поход на google.com - const mock = await this.browser.mock("https://google.com"); + const mock = await browser.mock("https://google.com"); // Указываем путь, откуда нужно взять фикстуру, а с помощью // "fetchResponse: false" говорим, что выполнять реальный поход не нужно mock.respond("./fixtures/my-google.com.html", { fetchResponse: false }); - await this.browser.url("https://google.com"); + await browser.url("https://google.com"); }); ``` @@ -155,14 +155,14 @@ it("should mock google.com and return answer from fixture", async function () { ## Пример 4: перенаправляем запрос с google.com на yandex.ru {#example_4} ```javascript -it("should redirect from google.com to yandex.ru", async function () { +it("should redirect from google.com to yandex.ru", async function ({browser}) { // Мокаем поход на google.com - const mock = await this.browser.mock("https://google.com"); + const mock = await browser.mock("https://google.com"); // Для редиректа необходимо просто указать урл mock.respond("https://yandex.ru"); - await this.browser.url("https://google.com"); + await browser.url("https://google.com"); }); ``` @@ -173,26 +173,26 @@ it("should redirect from google.com to yandex.ru", async function () { Заменим в ответе от _google.com_ все строки содержащие `Google` на `Yandex`: ```javascript -it("should modify response from google.com", async function () { +it("should modify response from google.com", async function ({browser}) { // Тут нужно мокать именно с www, так как переход на google.com // возвращает ответ 301 без body и перенаправляет нас на www - const mock = await this.browser.mock("https://www.google.com"); + const mock = await browser.mock("https://www.google.com"); mock.respond(req => { // С помощью регулярки заменяем "Google" на "Yandex" return req.body.replace(/Google/g, "Yandex"); }); - await this.browser.url("https://google.com"); + await browser.url("https://google.com"); }); ``` Кроме этого, мы можем видоизменять ответы от заранее неизвестных источников. Например, давайте модифицируем все скрипты, загружаемые на _google.com:_ ```javascript -it("should modify response from google.com", async function () { +it("should modify response from google.com", async function ({browser}) { // Первым аргументом указываем, что будем перехватывать абсолютно все запросы - const mock = await this.browser.mock("**", { + const mock = await browser.mock("**", { headers: headers => { // Фильтруем только запросы, в которых заголовок "content-type" // содержит значения "text/javascript" или "application/javascript" @@ -208,7 +208,7 @@ it("should modify response from google.com", async function () { return (req.body += `\nconsole.log("This script was modified in realtime");`); }); - await this.browser.url("https://google.com"); + await browser.url("https://google.com"); }); ``` @@ -217,11 +217,11 @@ it("should modify response from google.com", async function () { Предположим, что нам необходимо собрать список всех урлов, которые загружаются на странице. Используя эту информацию мы могли бы определить, есть ли у нас походы за внешними ресурсами или в соседние сервисы, которые мы никак не контролируем. Это означает, что они в любой момент могут не ответить и сломать нам тесты. Как мог бы выглядеть наш код: ```javascript -it("should mock yandex.ru and log all loaded urls", async function () { +it("should mock yandex.ru and log all loaded urls", async function ({browser}) { // Перехватываем абсолютно все запросы - const mock = await this.browser.mock("**"); + const mock = await browser.mock("**"); - await this.browser.url("https://yandex.ru"); + await browser.url("https://yandex.ru"); // mock.calls содержит не только информацию о посещенном урле, // Но также ответ от источника, хэдеры запроса, хэдеры ответа и т. д. @@ -235,7 +235,7 @@ it("should mock yandex.ru and log all loaded urls", async function () { Скорее всего, ваши тесты сложнее этих примеров и у вас будут различные клики в элементы, которые открываются в новых табах. В таких случаях предыдущий код ничего не узнает об открытии новых вкладок, а также о том, что в них тоже нужно собрать список урлов. Поэтому для такого случая нужно использовать API puppeteer'а: ```javascript -it("should mock yandex.ru and log all loaded urls (using puppeteer)", async function () { +it("should mock yandex.ru and log all loaded urls (using puppeteer)", async function ({browser}) { // В этой переменной будем накапливать список всех урлов const urls = []; @@ -249,7 +249,7 @@ it("should mock yandex.ru and log all loaded urls (using puppeteer)", async func } // Получаем инстанс puppeteer'а - const puppeteer = await this.browser.getPuppeteer(); + const puppeteer = await browser.getPuppeteer(); // Получаем все открытые страницы на текущий момент const pages = await puppeteer.pages(); @@ -274,10 +274,10 @@ it("should mock yandex.ru and log all loaded urls (using puppeteer)", async func urlsHandler(page); }); - await this.browser.url("https://yandex.ru"); + await browser.url("https://yandex.ru"); // Находим первым элемент в списке сервисов (на тот момент была страница с футболом) - const elem = await this.browser.$(".services-new__list-item > a"); + const elem = await browser.$(".services-new__list-item > a"); // Выполняем клик в сервис, который открывается в новой вкладке await elem.click(); @@ -298,20 +298,20 @@ module.exports = { "testplane-global-hook": { enabled: true, - beforeEach: async function () { + beforeEach: async function ({browser}) { // Проверяем, что имя браузера не начинается на "chrome" - if (!/^chrome$/i.test(this.browser.capabilities.browserName)) { + if (!/^chrome$/i.test(browser.capabilities.browserName)) { return; } // Мокаем поход на google.com - const mock = await this.browser.mock("https://google.com"); + const mock = await browser.mock("https://google.com"); mock.respond("hello world", { fetchResponse: false }); }, - afterEach: function () { + afterEach: function ({browser}) { // Очищаем все моки в текущей сессии - this.browser.mockRestoreAll(); + browser.mockRestoreAll(); }, }, @@ -327,8 +327,8 @@ module.exports = { ```javascript // Явно укажем, чтобы тест выполнялся только в браузерах, название которых начинается с chrome testplane.only.in(/^chrome/); -it("should mock google.com inside global before each", async function () { - await this.browser.url("https://google.com"); +it("should mock google.com inside global before each", async function ({browser}) { + await browser.url("https://google.com"); }); ``` diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/guides/how-to-manage-cpu-performance.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/guides/how-to-manage-cpu-performance.mdx index eec26b7..2300905 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/guides/how-to-manage-cpu-performance.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/guides/how-to-manage-cpu-performance.mdx @@ -18,9 +18,9 @@ import Admonition from "@theme/Admonition"; Воспользуемся этим методом, чтобы замедлить скорость процессора в 8 раз: ```javascript -it("should open yandex.ru with emulation 8x slower CPU", async function () { +it("should open yandex.ru with emulation 8x slower CPU", async function ({browser}) { // Получаем инстанс puppeteer'а - const puppeteer = await this.browser.getPuppeteer(); + const puppeteer = await browser.getPuppeteer(); // Получаем первую открытую страницу (считаем, что она активная в данный момент) const [page] = await puppeteer.pages(); @@ -28,7 +28,7 @@ it("should open yandex.ru with emulation 8x slower CPU", async function () { // Замедляем скорость процессора в 8 раз await page.emulateCPUThrottling(8); - await this.browser.url("https://yandex.ru"); + await browser.url("https://yandex.ru"); }); ``` @@ -39,9 +39,9 @@ it("should open yandex.ru with emulation 8x slower CPU", async function () { Однако это ограничение можно было обойти с помощью метода _puppeteer_ [CDPSession.send()][cdp-session-send], отправив браузеру команду [Emulation.setCPUThrottlingRate][emulation-set-cpu-throttling-rate] по CDP: ```javascript -it("should open yandex.ru with emulation 8x slower CPU", async function () { +it("should open yandex.ru with emulation 8x slower CPU", async function ({browser}) { // Получаем инстанс puppeteer'а - const puppeteer = await this.browser.getPuppeteer(); + const puppeteer = await browser.getPuppeteer(); // Получаем первую открытую страницу (считаем, что она активная в данный момент) const [page] = await puppeteer.pages(); @@ -52,7 +52,7 @@ it("should open yandex.ru with emulation 8x slower CPU", async function () { // Замедляем скорость процессора в 8 раз await client.send("Emulation.setCPUThrottlingRate", { rate: 8 }); - await this.browser.url("https://yandex.ru"); + await browser.url("https://yandex.ru"); }); ``` diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/guides/how-to-manage-network-bandwidth.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/guides/how-to-manage-network-bandwidth.mdx index 8641ff7..1964949 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/guides/how-to-manage-network-bandwidth.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/guides/how-to-manage-network-bandwidth.mdx @@ -28,11 +28,11 @@ import Admonition from "@theme/Admonition"; Сэмулируем 2G-соединение и откроем yandex.ru в Хроме с эмуляцией телефона: ```javascript -it("should open yandex.ru with emulation of 2G-connection", async function () { +it("should open yandex.ru with emulation of 2G-connection", async function ({browser}) { // Имитируем 2G-соединение - await this.browser.throttle("Good2G"); + await browser.throttle("Good2G"); - await this.browser.url("https://yandex.ru"); + await browser.url("https://yandex.ru"); }); ``` @@ -41,16 +41,16 @@ it("should open yandex.ru with emulation of 2G-connection", async function () { Также мы можем сэмулировать соединение с конкретными характеристиками: ```javascript -it("should open yandex.ru with emulation of custom connection", async function () { +it("should open yandex.ru with emulation of custom connection", async function ({browser}) { // Имитируем соединение в сети с заданными характеристиками - await this.browser.throttle({ + await browser.throttle({ offline: false, // имитация отключения от интернета downloadThroughput: (10 * 1024) / 8, // максимальная пропускная способность загрузки (byte/sec) uploadThroughput: (10 * 1024) / 8, // максимальная пропускная способность отправки (byte/sec) latency: 10, // минимальная задержка от отправки запроса до получения заголовков ответа }); - await this.browser.url("https://yandex.ru"); + await browser.url("https://yandex.ru"); }); ``` diff --git a/i18n/ru/docusaurus-plugin-content-docs/current/plugins/testplane-global-hook.mdx b/i18n/ru/docusaurus-plugin-content-docs/current/plugins/testplane-global-hook.mdx index 1dcaaae..b4e9782 100644 --- a/i18n/ru/docusaurus-plugin-content-docs/current/plugins/testplane-global-hook.mdx +++ b/i18n/ru/docusaurus-plugin-content-docs/current/plugins/testplane-global-hook.mdx @@ -30,11 +30,11 @@ npm install -D testplane-global-hook module.exports = { plugins: { "testplane-global-hook": { - beforeEach: async function () { - await this.browser.deleteCookie(); // Например, мы хотим всегда очищать cookies перед запуском теста + beforeEach: async function ({browser}) { + await browser.deleteCookie(); // Например, мы хотим всегда очищать cookies перед запуском теста }, - afterEach: async function () { - await this.browser.execute(function () { + afterEach: async function ({browser}) { + await browser.execute(function () { try { localStorage.clear(); // И всегда очищать за собой localStorage после завершения теста } catch (e) {} @@ -52,15 +52,35 @@ module.exports = { ### Расшифровка параметров конфигурации {#setup_description} - - - - - - - - - + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
**Параметр****Тип****По умолчанию****Описание**
enabledBooleantrueВключить / отключить плагин.
beforeEachFunctionnullАсинхронная функция-обработчик, которая будет выполняться перед запуском каждого теста.
afterEachFunctionnullАсинхронная функция-обработчик, которая будет выполняться после завершения каждого теста.
**Параметр****Тип****По умолчанию****Описание**
enabledBooleantrueВключить / отключить плагин.
beforeEachFunctionnullАсинхронная функция-обработчик, которая будет выполняться перед запуском каждого теста.
afterEachFunctionnullАсинхронная функция-обработчик, которая будет выполняться после завершения каждого теста.
## Полезные ссылки {#useful_links}