How to run Chrome headless in Selenium

How to run Chrome headless in Selenium

In this article, you will learn how to run the Chrome headless in Selenium WebDriver. What is really means is that your tests will run without opening the Chrome browser.

Table of contents

Introduction

Did you know that it is possible to run an automated test without actually opening a browser window? This practice is referred to as running a test in headless mode. A browser driver is still needed although a browser is not needed. I’m going to show you how to use ChromeDriver to run tests in headless mode.

But before we move on, you may be wondering what are the advantages and disadvantages of running tests in headless mode. Let’s take a look at that next.

Advantages & disadvantages of using headless mode

Believe it or not there are some advantages to running tests in this way and they are listed below.

  • Your tests will consume less resources from the system that they run on. Mainly because there won’t be a need to open a browser. This may be more noticeable when you are running tests in parallel and are using a significant number of concurrent threads.
  • You may notice a slight improvement in test execution time. It is a result of not needing to open a browser. Moreover, there is no need to display the user interface (UI) elements on the screen.

With advantages one can also expect disadvantages. Below is a list of some of those.

  • Tests will become more difficult to debug. The fact that you can’t see what is happening when a test runs, makes it more difficult during the debugging process.

How does headless mode work?

You may be wondering how WebDriver is going to be able to find elements and click of them when no browser window will open. What happens is that whatever website you visit is rendered in memory. This is how WebDriver is able to locate elements.

Another thing to note here is that you will still be able to take a screenshot of a web page or a web element when running in headless mode!

How to run Chrome in headless mode

In order to run your tests in headless mode, you will need to use the ChromeOptions as follows.

ChromeOptions options = new ChromeOptions();
options.addArguments("--headless");

By using setHeadless() method, you will accomplish the same result as shown below.

ChromeOptions options = new ChromeOptions();
options.setHeadless(true);

Lastly, you need to pass the options as an argument when instantiating the ChromeDriver.

ChromeOptions options = new ChromeOptions();
options.setHeadless(true);
WebDriver driver = new ChromeDriver(options);

If you would like to see how to run Chrome headless in Selenium, watch the following video.

Conclusion

Running tests in headless mode can be advantageous when system resources are a concern or when you need your tests to run a little bit faster. However, you should not expect a great decrease in test execution times.

Leave a Reply