Rayrun
← Back to Discord Forum

Expect Styles.css to return 200 OK test

Hi,

I have passing tests even though my style.css will fail to load, due to an environment configuration issue.

I want to write a playwright test that expects styles.css and other CSS files to load with a 200 response.

I've had a search but can't find anything with examples, would someone be able to tell me if this is possible and point me in right direction?

Cheers!

This thread is trying to answer question "How can I write a playwright test that expects styles.css and other CSS files to load with a 200 response?"

2 replies

There are a couple ways to approach this, the easiest would be to pick a style that is included within the css and assert on it from a built in assertion

Another way to go about this would be to create a variable stylesLoaded = false

and use page.route to route all requests, once styles.css is loaded within the page.route set the stylesLoaded = true

then do an assertion after all network requests have completed to expect(stylesLoaded).toBe(true)

@butchmayhew Ah yes! Page.routes! I had thought there would be a way. I'll look into that to learn more with routes.

Yeah, I went with the easiest way by expecting a background colour, which works, but I like the routes idea

Much appreciated, thank you!

Answer

Sure, you can use Playwright's APIs to monitor and modify network traffic, including HTTP requests. This allows you to track the network requests made by a page and verify their responses.

Here's how you can do it:

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

test('CSS file loads with 200 response', async ({ page }) => {
  // Block any css requests for each test in this file.
  await page.route(/\.css$/, route => route.abort());

  await page.goto('https://ray.run');

  // Assert that the CSS file loaded successfully
  const cssResponse = await page.waitForResponse(response => response.url().endsWith('.css'));
  
  expect(cssResponse.status()).toBe(200);
});

In this code, page.route() is used to intercept any request with a URL ending in ".css" and abort it. Then, we navigate to our target webpage using page.goto(). After that, we use page.waitForResponse() to wait for the response of the CSS file request. Finally, we assert that the status code of the response is equal to 200 using expect().

This way, you can create detailed tests that ensure your CSS files are loading correctly with a successful HTTP status code (200).

Related Discord Threads

TwitterGitHubLinkedIn
AboutQuestionsDiscord ForumBrowser ExtensionTagsQA Jobs

Rayrun is a community for QA engineers. I am constantly looking for new ways to add value to people learning Playwright and other browser automation frameworks. If you have feedback, email luc@ray.run.