Stimulate network throttling in Playwright (Typescript/JavaScript)

Overview

In this previous article, I already show you how easily to stimulate network throttling in Selenium Java for Chrome. It is also very easy to apply for Playwright (Typescript/JavaScript).

If you do not know how to create a basic project with Playwright (Typescript), please just refer to Playwright docs first.

Stimulate network throttle for Chromium browser (Chrome/MS Edge)

Full code with comment as explanation as below (test.spec.ts)

import { test }  from "@playwright/test";

test("Emulate network throttle", async ({page}) => {

    // create a new CDP session (only support Chrominum browser)
  const client = await page.context().newCDPSession(page);

  // enable network emulation
  await client.send("Network.enable");

  // change network conditions with specific params
  await client.send("Network.emulateNetworkConditions", {
    offline: false,
    downloadThroughput: ((500 * 1000) / 8) * 0.8,
    uploadThroughput: ((500 * 1000) / 8) * 0.8,
    latency: 70,
  });

  // go to specific URL and watch logged time 
  const start = new Date().getTime();
  await page.goto("https://ericsson.com/");
  console.log((new Date().getTime() - start) / 1000);

});

Run this above code and watch logged time. As you can see it is noticeably slow. First time, it takes ~11 seconds to finish running. After that I just commented all lines related to emulate network throttling, it run much faster and only takes no more than 1 second.

* Note that you need to focus on these parameters to get real network throttling (as “Slow 3G”):

+ offline: false

+ downloadThroughput: 376Kbps

+ uploadThroughput: 376Kbps

+ latency (RTT – round-time trip): 2000 ms

If you do not know clearly about these params, do some Google search first. You can also refer to this.

Conclusion

Stimulate network throttling in Playwright is quite easier and less code than Selenium, I think. Know this technique can help you breezily in some automated case. If you are interested in how to do the same thing for Selenium, please read this article. Thanks for reading!

Ask me anything