Testing code might not sound like the most fun experience you can imagine as a programmer, good news that you can automate it. This post will go through how to automatically launch your browser using Selenium and programmatically act as a user to login in to a web service. We will use Netflix as an example for demo purposes only, but please note that we are not in any way affiliated with Netflix’ services or the trademark. The script is partly similar to that of our previous post using Protractor for testing an Angular web app, however this automated test is disconnected from Angular and based on Node.js.
What components do you need?
- Node.js installed (here is a link for download)
- Selenium installed (you can do a ’npm install selenium-webdriver’ if you have Node.js installed)
- WebdriverIO installed (’npm install webdriverio’)
That’s it! We’re ready to go!
Creating the test
We start by creating an empty folder with two files: conf.js and autologin.js. The file ’conf.js’ is just a configuration file to tell Selenium which browser to use, test frameworks etc. You could either create your config file through the command line wizard by typing wdio config
in the Terminal window or copy ours from gitlab.com/yellington/WebdriverIO. If you use the command line wizard, note that we have manually fine tuned two entries below. Since we put the conf.js and autologin.js files in the same folder, the specs path in the conf.js file has to point to autologin.js residing in the same folder.
[code lang=”js” gutter=”false”]
specs: [
’autologin.js’
],
[/code]
We also extend the timeout for the tests to ’99999999’ to make sure we have plenty of time to manipulate the login sequence.
[code lang=”js” gutter=”false”]
mochaOpts: {
ui: ’bdd’,
timeout: 99999999
},
[/code]
The conf.js file can specify a lot more parameters such as which web browser you prefer to run the tests on.
Programming the login sequence
Downloading the HTML page and traversing trough it is a quite dirty way of interfacing a web service. However, it is a good demo of how you can interact with a web service that does not provide an official web API. The login sequence in the autologin.js file is test runner based and use synchronous calls. You can download it from gitlab.com/yellington/WebdriverIO and it looks like:
[code lang=”js”]
var loginData = require(’./login.json’);
describe(’Automatical login to Netflix’, function() {
it(’should step through to the main movie page’, function () {
//Open the login page for Netflix
browser.url(’https://www.netflix.com/Login’);
//Identify the input fields for email and password by finding the first