How to use Chrome Headless with Behat

This article was published more than 6 months ago, this means the content may be out of date or no longer relevant.

Headless Chrome is shipping in Chrome 59 (currently in beta), it seems that we can use the browser without UI. It is very interesting for testing and automated purpose. In this post, we are going to configure Behat (a PHP framework for autotesting your business expectations) to use Chrome in headless mode.

This new Chrome feature interest a large part of the Web community. So much, that the maintainer of PhantomJS, a headless browser which is also based on Webkit, announced the end of the project. So, if you used this in your Behat scenarios, you should change the browser you used.

This is an sample of the Behat configuration I use for PhantomJS :

# behat.yml
default:
    extensions:
        # ...
        Behat\MinkExtension:
            base_url: http://project.dev
            sessions:
                default:
                    selenium2:
                        wd_host: http://localhost:4444/wd/hub

Now we have to make some change to be able to use Chrome browser. First, we have to add the ChromeDriver. Next, we need to add some configuration directory in our behat.yml file :

# behat.yml
default:
    extensions:
        # ...
        Behat\MinkExtension:
            base_url: http://project.dev
            sessions:
                default:
                    selenium2:
                        browser: chrome
                        wd_host: http://localhost:4444/wd/hub
                        capabilities:
                            chrome:
                                switches:
                                    - "--headless"
                                    - "--disable-gpu"

There are some little changes if the configuration file. We begin by defining the browser we want to use. Then we set up some capabilities (options that can add to customize and configure our Chrome session). We add the --headless argument to use the headless mode in combination to --disable-gpu which is temporarily needed for now.

Et voilà ! By adding 5 lines of configuration we have replaced the PhantomJS browser usage by Google Chrome with “headless” mode.

The full configuration file is available on Gist