Skip to content

Selenium Docker: Testing local applications

Simon Tsvilik edited this page Sep 7, 2020 · 9 revisions

Use Case

As a developer I would like to run functional tests against my local application (running on localhost) and use docker-selenium as my testing environment.

How is this different from running tests against a public site? (link)

Great question! Well, it just happens that when docker container is running it has its own localhost which is relative to its container and has no awareness of localhost running on the host OS. This is a problem since now you can not instruct selenium to browse to localhost (i.e. browser.open("http://localhost:8000");). How do we solve this problem? Answer is simple - we use docker option --add-host to map a hostname that would point to our machine IP. Basically we create an alias in the docker that would translate some hostname to IP address of our machine.

Test process flow explained

  1. We start-up our web application locally (say on port 8000) and bind it to either 0.0.0.0 or 127.0.0.1 address.
  2. wdio-docker-service will start a Selenium Docker image of your choice and configure it to resolve dockerhost to an internal IP (i.e. 192.168.1.101).
  3. Once service is running (normally on port 4444), tests will run (inside a container).
  4. Once tests are finished wdio will report back results.

How do I configure that?

In our configuration we want to use baseUrl pointing to a domain name understood by docker container, and map that domain name dockerhost to an IP address of our machine 192.168.1.101 (of course it would be different for your machine).

Example:

//wdio.conf.js
exports.config = {
    host: 'localhost',
    path: '/wd/hub', // Required to work with wdio v6
    specs: [
        './test/*.js'
    ],

    capabilities: [{
        browserName: 'chrome'
    }],

    sync: true,
    logLevel: 'debug',

    baseUrl: 'http://dockerhost:8000',

    waitforTimeout: 10000,
    connectionRetryTimeout: 90000,
    connectionRetryCount: 3,

    framework: 'mocha',
    mochaOpts: {
        ui: 'bdd'
    },

    services: ['docker'],
    dockerLogs: './',
    dockerOptions: {
        image: 'selenium/standalone-chrome',
        healthCheck: 'http://localhost:4444',
        options: {
            p: ['4444:4444'],
            addHost: ['dockerhost:192.168.1.101'],
            shmSize: '2g'
        }
    }
};

Important parts above are baseUrl, addHost.

  • baseUrl - base url used for your tests. In this scenario it points to domain we mapped to our local IP.
  • addHost - a docker command which maps a hostname to an IP address (i.e. <hostname>:<ip_address>).
Clone this wiki locally