Skip to main content

Quality Assurance

Optimizing Test Scenarios: Testing Failed Network Requests with Selenium CDP Commands

Istock 1355632594

In our exploration of Selenium Chrome DevTools integration, we’ve covered simulating mobile browsing, harnessing real-time insights with Selenium CDP Listeners, and mastering the art of intercepting and mocking network/API responses. Our journey now advances into the realm of optimizing test scenarios by addressing failed network requests. In this article, we’ll navigate through a comprehensive guide on testing and handling failed network requests using Selenium CDP commands.

To catch up on our previous blogs:

Simulating Mobile Browsing: https://blogs.perficient.com/2024/01/22/optimizing-web-testing-mastering-mobile-simulation-with-selenium-cdp-device-metrics-override/

Selenium CDP Listeners: https://blogs.perficient.com/2024/01/24/decoding-web-interactions-unleashing-selenium-cdp-listeners-to-extract-network-responses/

Intercepting and Mocking Network/API Responses: https://blogs.perficient.com/2024/01/30/intercepting-and-mocking-network-responses-with-selenium-chrome-devtools/

Detecting and Responding to Failed Network Requests

In the dynamic landscape of web testing, handling failed network requests is crucial for robust test scenarios. Failed requests can lead to unexpected application behavior, and identifying and responding to these issues is paramount. Selenium and Chrome DevTools Protocol (CDP) commands offer a powerful solution to tackle this challenge.

How to Test and Handle Failed Network Requests

Let’s delve into a step-by-step guide on how to test and handle failed network requests using Selenium CDP commands:

Failing Network Request

Similar to the way we mocked a network request, we can fail a network request intentionally to perform the test on the failed network request, e.g., to check if an error message pops up when the error occurs. Let us understand it with a simple scenario. We have a sample website https://rahulshettyacademy.com/angularAppdemo, with a “Virtual Library” link that navigates to the Library page that displays the list of books.. We will pause and fail the request for the request URL: “https://rahulshettyacademy.com/Library/GetBook.php?AuthorName=shetty”, which is responsible for showing the book records on the  Library page. When we fail the given particular request, no records should be shown.

Step-by-step Guide to Fail Network Request

Below is the step-by-step code with an explanation for the action:

public class FailedRequest {

    public static void main(String[] args) throws InterruptedException {

        //initialize driver
        WebDriverManager.chromedriver().setup();
        ChromeDriver driver  = new ChromeDriver();
        
        //create devTools session
        DevTools devTools = driver.getDevTools();
        
        devTools.createSession();
        
        //Create Request Pattern Object to define the particular URL we want to target, as we don't want to apply failRequest method on all netowrk calls
        //we will pass only the first argument i.e. urlType for the Request Pattern class object.  
        Optional<List<RequestPattern>> pattern= Optional.of(Arrays.asList(new RequestPattern(Optional.of("*GetBook*"),Optional.empty(),Optional.empty())));
        
        //enable fetch method with pattern object argument to target the specific URL call
        devTools.send(Fetch.enable(pattern, Optional.empty()));
        
        //Pause the request and then fail the request for given url using the failRequest method
        devTools.addListener(Fetch.requestPaused(),request -> {
            
            //failrequest method accepts argument: requestID and ErrorReason (Allowed Values: Failed, Aborted, TimedOut, AccessDenied, ConnectionClosed, ConnectionReset, ConnectionRefused, ConnectionAborted, ConnectionFailed, NameNotResolved, InternetDisconnected, AddressUnreachable, BlockedByClient, BlockedByResponse)
                devTools.send(Fetch.failRequest(request.getRequestId(), ErrorReason.FAILED)); 
            });
        
        //perform the test
        driver.get("https://rahulshettyacademy.com/angularAppdemo/");
        driver.findElement(By.cssSelector("button[routerlink*='library']")).click();
        Thread.sleep(5000);
        
        //You can observe that no records are shown on the Library Page as we have failed the request 
        //Note the sample website we are using is not designed to show error message on request failure, hence we are not validating it, but in realtime applications we can validate the error message that shows after request failure
        
        //close the driver
        driver.quit();

    }

}

Hence, by following the above process, we can fail a request and test the request failure.

You can refer to official documentation for more details on various methods and events: Chrome DevTools Protocol

Conclusion

Testing and handling failed network requests with Selenium CDP commands provide a proactive approach to ensure the robustness of web applications. By leveraging the capabilities of Chrome DevTools Protocol, testers can detect and respond to failed requests in real time, enhancing the reliability and effectiveness of their test scenarios. Stay tuned for more insights as our Selenium Chrome DevTools integration series continues to explore advanced web testing techniques. Happy testing!

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Himanshu Pawar

Himanshu Pawar works in Quality assurance at Perficient, based out of India. He is currently working on Adobe technologies. Himanshu is a technology enthusiast passionate about automation and automation tools. He constantly seeks opportunities to learn and explore new technologies.

More from this Author

Categories
Follow Us