Protractor with visual studio code and javaScript/typeScript

Pre – Requisites:

Visual Studio Code Installed

Node Js Installed

(All commands will be in italics)

Setup of Project :

Steps:

Open Visual Studio code and add new folder.

Step 2 : Init the npm for the package.json file.

Open Terminal from Terminal – > New Terminal

Use below command

npm init

Enter all details – some dummy details, for lisence details you can simply hit enter to generate dummy configuration

After all select yes.

Now you will see the package.json file in the left

Now install protractor locally with following command

npm install –save protractor

if you see below error change the protractor to protractor 2 in the json file and try again

Install

npm install –save jasmine

Install

npm install –save typescript

Create new folder called specs

Create folder inside specs and keep driver inside it.

Now its time to create tsconfig.json file for the configuration of type script.

{

    “compilerOptions”: {

       //ts “module”:”commonjs”,

        “noImplicitAny”: true,

        “removeComments”: true,

        “preserveConstEnums”: true,

        “moduleResolution”: “node”,

        “sourceMap”: true,

        “types”:[“jasmine”]

    },

    “typeRoots”: [

        “node_modules/@types”

      ],

    “exclude”: [

       “node_modules”,

        “**/*.spec.ts”

    ]

}

Tsconfig.json file is configuration of the tsc compiler.

We are going to use typescript and typescript compiler to compile the code and convert to java script.

Now create the script for our selenium test with scripts.ts in the specs.

Once we start writing the test we don’t see this in the code console, only type script and jasmine are seen. Let us fix this.

Install

npm install -d @types/jest

update the package.json file with below content.

{

  “name”: “typescript”,

  “version”: “1.1.0”,

  “description”: “test”,

  “main”: “config.js”,

  “dependencies”: {

    “@types/jasmine”: “^3.5.11”,

    “@types/jest”: “^26.0.3”,

    “@types/mocha”: “^7.0.2”,

    “jasmine”: “^3.5.0”,

    “protractor”: “^7.0.0”,

    “typescript”: “^3.9.5”

  },

  “devDependencies”: {},

  “scripts”: {

    “test”: “test”

  },

  “repository”: {

    “type”: “git”,

    “url”: “test”

  },

  “keywords”: [

    “test”

  ],

  “author”: “test”,

  “license”: “ISC”

}

Also re-install the protractor, if its not got installed already.

npm install –save protractor

 now create test script which opens the google and enters some text.

import {browser, element, by} from ‘protractor’

import {} from ‘jasmine’

    describe(‘sanity’, ()=>

    {

        it(‘expected valuidations’, ()=>

        {

            browser.ignoreSynchronization=true;

            //browser.manage().timeouts().pageLoadTimeout(180000);

            browser.get(‘http://google.com’,100000).then(()=>console.log(‘browserOPened’)).then(

                ()=>

                {

                    browser.getTitle().then((title:string)=>console.log(title));

                }

            ).then ( ()=>

            {

                element(by.name(‘q’)).sendKeys(‘ConsolidatedChoas’).then( ()=>

                {

                    element(by.name(‘btnK’)).click();

        });

        }

        )

    });

})

Now we need to convert this to java script code wit tsc

Run following command and observe the changes.

tsc

Now the code gets compiled and you see new file gets generated in the folder.

Now to run the protractor, we need config.js file which tells the chrome browser for to take the options and capabilities.

Config.js — below

exports.config = {

    // launch locally when fields directConnect and seleniumAddress are not provided

    chromeDriver: ‘./specs/driver/chromedriver.exe’,

    specs: [‘./specs/scripts.js’],

    capabilities: {

      browserName: ‘chrome’,

      chromeOptions: {

        args: [“–headless”, “–disable-gpu”, “–window-size=800×600”]

    }

    }

  }

Now we are all ready to run our first script.

For running follow below step.

Protractor config.js

The result should display as below.

Points to be Noted:

  • Package.json must have all the modules you are using for compiler to understand
  • Tsconfig.json must have include and exclude what you want to include exclude while compiling the code
  • MOST IMPORTANTLY EVERY TIME YOU MAKE CHANGES TO TYPESCRIPT FILE, YOU NEED TO USE TSC COMMAND TO REGENERATE THE JAVA SCRIPT FILES.
  • The chrome can be invoked headless or with UI, in this we illustrated headless mode.
  • Check the modules, types that are listed in config files and make sure that you have those in the npm_modules folder for verification.
  • Following is link for the git project.

Advertisement

Protractor setup and example of non angular app simple test – Part 2

In the Part 1 we have seen how to setup the protractor, In this section lets see how to write test spec file and configure the formatted report.

googleTest spec file has below content.

browser.ignoreSynchronization=true;
//The above line is specifically written for non angular applications such as google
browser.driver.sleep(5000);
//Describe the test and expected result in it block
describe('google homepage', function() {
it('should open the page', function() {
var waitEC = protractor.ExpectedConditions;
browser.driver.get('https://google.com');
browser.driver.sleep(5000);
browser.driver.findElement(by.name('q')).sendKeys('Testing Example for Protractor non angular');
browser.driver.sleep(1000);
expect('Testing Example for Protractor non angular').toEqual('Testing Example for Protractor non angular');
});
})
describe('click on search', function() {
it('should click on search button', function() {
browser.driver.findElement(by.name('btnK')).click()
});
});

The above code is for the protractor spec file to open the google website and search for specific keywork and click on google search button. In the next section will see the formatting part.

As we know, we have different types of formats available for the protractor, among those below is widely used as it is fortmatted console and does not require additional css or etc files to view the results. All results are shown on the console logs it self.

we need to first install the node package for this.  More info jasmine formatter

npm install jasmine-spec-reporter

Once we install the package, it will download necessary module under protractor location.

Once downloaded, we just need to update our conf file with the downloaded formatter.

The sample conf file also given in the above site. Following is the sample conf file used for our googleTest spec.

let SpecReporter = require('jasmine-spec-reporter').SpecReporter;

exports.config = {
framework: 'jasmine2',
jasmineNodeOpts: {
showColors: true,
silent: true,
defaultTimeoutInterval: 360000,
print: function () {
}
},
specs: [
'googleTest.js'
],
capabilities: {
browserName: 'chrome',
'chromeOptions': {
args: ['--test-type']
}
},
logLevel: 'WARN',
onPrepare: function () {
jasmine.getEnv().addReporter(new SpecReporter({
spec: {
displayStacktrace: true
},
summary: {
displayDuration: false
}
}));
}
};

Once we have updated editing the conf file. you will be able to see report in nice colored format shown below.

Result

Please write to me or down below comments section if you are facing any advanced issues in protractor.

Thanks for reading..!!!

Protractor setup and example of non angular app simple test – Part 1

Now a days we see lot of angular JS applications being built.

It is said that at least 10% of the latest developing are based on angular js.

In this section we see how to configure and run a simple protractor test on angular and non angular app

Its very straight forward, mostly thats the reason why its largely adapted.

Step 1 :

Install Node.js, current version of node js when writing this blog is v10.16.2

you can download node js from  Node Js download

select the windows MSI and install it. While installing it select add node js to path.

This option enable us to directly access node commands from cmd without navigating to node directory.

Node JS is like collection of several java script libraries. They are called as node modules

The installation also installs the node package manager which is required to install different node modules.

Once you have installed it  go to command prompt (search-> run – >cmd)

then enter following command

Node -v

It should show the current installed version, if its not there is some issue with the installation.

Step2:

Now we have node js setup and ready

Open cmd and try to install the protractor, install protractor globally (all users on the machine, if not remove -g)

npm install protractor -g

More information on this site https://www.protractortest.org/#/

Usually protractor sets up the web driver manager. But if it’s not then you need to install the webdriver manager as well

webdriver-manager update

Step3:

Now we have to start our webdriver-manager to kick of the example test

Webdriver manager will look for webdriver connections that are being initiated by protractor.

webdriver-manager start

There is one sample test that comes with protractor we can use it and create couple of more tests.

But, if we want to run on google we might want to make some changes.

At the end of start of webdriver you should see command prompt like below.

Capture

Step4:

Once you started the webdriver manager, open another command prompt and run a angular example test

In the node js installation will happen typically in appdata/roaming folder go to following path, you should see following

Example path :

C:\Users\{user_name}\AppData\Roaming\npm\node_modules\protractor\example

You should see the following, googleTest is something I have added, you don’t see it by default.

scriptlocation

To run a test we need to use following command

Protractor C:\Users\{user_name}\AppData\Roaming\npm\node_modules\protractor\example\conf.js

What does this mean ?

Protractor reads the conf file and executes the specification file mentioned in the conf.js

Protractor uses something called Jasmin framework by default. Its called as “Describe It” framework.

Test start with Describe() – > then It() , which means action and its expected outcome.

All the code is written in java script, we can use type script too.

Once we start the example test it will perform operations on node js site and gives us the following result.

The result displayed below is formatted, I will mention how to configure different types of reports in next section.

Result

In the next part will discuss about following

  • Custom report as shown above.
  • conf.js sections and how to edit.
  • googleTest.js -> non angular application example.