Running Angular unit tests in headless Chrome

Setting up Karma to run unit tests in headless chrome

Posted on August 21, 2018

Tags:

Angular

I’ve come across an issue where unit tests were failing on my CI server when using PhantomJS but passing locally. To get around this I set up Karma to user headless Chrome which solved the issue.

To setup headless chrome you’ll first need to install the karma-chrome-launcher and add it as a plugin to your Karma config (I’m omitting my full config so you can see what needs to be added):

npm install karma-chrome-launcher --save-dev
module.exports = function (config) {
    config.set({
        plugins: [
            require('karma-chrome-launcher')
        ]
    });
};

Next it’s just a case of adding a custom launcher and updating the browser value in the config:

module.exports = function (config) {
    config.set({
        plugins: [
            require('karma-chrome-launcher')
        ],
        customLaunchers: {
            'chrome_headless': {
                base: 'Chrome',
                options: {
                    windowName: 'test-window',
                    settings: {
                        webSecurityEnabled: false
                    }
                },
                flags: ['--headless', '--remote-debugging-port=9222', '--disable-web-security'],
                debug: true
            }
        },
        browsers: ['chrome_headless']
};