Thursday, September 21Be an Automation Engineer

Protractor example with Typescript

Before writing our first protractor test, it is better to read a bit about type script.

Why to use TypeScript?

Problem with Javascript:
We need not to follow any strict typings like defining variables and following strict syntaxes while writing a script using plain Javascript. This will make the code clumsy and readability will also be a problem.
Uses of TypeScript:
Microsoft has designed Type script to enable developers to use highly-productive development tools and practices like static checking and code refactoring when developing JavaScript applications. Typescript will also has ability to provide intellisense through editors like ‘Atom’, ‘Sublime’, ‘VisualStudio’, ‘Vim’ and ‘Webstorm’ etc.. So Typescript will make developers life easy. But the obvious thing is Typescript will be converted to plain Javascript because all the existing browsers can not understand Typescript.

Basically typescript is a typed superset of Javascript and complies to pain Javascript. You can learn about type script and it’s syntax here.

1. Install Protractor if you have not installed it:

Click here to go through step by process of installing protractor in Windows/MAC machines.

If you have not set up protractor project stucture, please follow Step 2 and Step 3 otherwise goto Step 4.

2. Install editor of your choice:

You can install your preferred editor to write tests or you can download and install ‘Atom‘ if you are not sure.

3. Creating project structure:

In Windows command prompt:

Navigate to your preferred drive( Example: D: to navigate to D drive) and execute below command.

D:
mkdir ProtractorAutomation
cd ProtractorAutomation

Run below command to create subdirectories

mkdir specs

In Mac OS Terminal:

Navigate to your Documents Section

cd $User 
cd Documents

Execute below command to create project folder.
mkdir -p ./ProtractorAutomation
cd ProtractorAutomation

Run below command to create subdirectories
mkdir -p ./specs

Your Project Structure would be like below image.
protractor-empty-project-structure

4. Install and configure Typescript:

Navigate to your project folder and run the below command to install protractor locally.

npm install protractor

Run the below command to install type script globally.
npm install -g typescript

As we are using ‘Node.js’ and ‘Jasmine’ framework. We need to install ‘typings’ of node and jasmine.
Run the below commands to install ‘@types/jasmine’ and ‘@types/node’.
npm install @types/jasmine
npm install @types/node

Lets create the below package.json in your Project folder.
package.json

{
  "name": "protractorautomation",
  "version": "1.0.0",
  "description": "Protractor Typescript automation framework",
  "main": "config.js",
  "dependencies": {
    "protractor": "^4.0.11"
  },
  "devDependencies": {},
  "scripts": {
    "pretest": "npm run tsc",
    "test": "protractor ConvertedJSFiles/config.js",
     "tsc": "tsc"
  },
  "keywords": [
    "Protractor",
    "Typescript"
  ],
  "author": "Vijay Daram",
  "license": "ISC"
}

Under “Script”: section, we have configured to run js files generated from Typescript. They will be generated under ConvertedJSFiles folder in your project.

Now, it’s time to configure typescript.
Create a below tsconfig.json file in your project folder.

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": false,
    "declaration": false,
    "removeComments": false,
    "noImplicitAny": false,
    "outDir": "ConvertedJSFiles",
    "types": ["jasmine", "node"]
  },
  "exclude": [
    "node_modules"
  ]
}

We have mentioned that ‘ConvertedJSFiles’ as output directory for Js files returned form Typescript files. Here we are excluding ‘node_modules’ why because the node_modules may contain may “.ts” files which are not needed to be converted to javascript.
After creating tsconfig.js and package.json your project structure would look like below.
protractor-file-structure-with-typescript-configuration-files

We have completed configuring typescript. Lets dive into writing our first script.

5. How to write?

Create FistSpec.ts in ProtractorAutomation->specs.
FirstSpec.ts

import { ElementFinder, browser, by, element } from 'protractor';
describe('angularjs homepage todo list', function () { //Suite in Jasmine
  it('should add a todo', function () { // Test in Jasmine
    browser.get('https://angularjs.org'); // Entering application url in browser
    // Enter text under TODO
    element(by.model('todoList.todoText')).sendKeys('write first protractor test');
    element(by.css('[value="add"]')).click(); // Clicks on 'Add' button
    // Getting all Todo lists displayed
    element.all(by.repeater('todo in')).then(function (todoList) {
      // Asserting the TODO's count as 3
      expect(todoList.length.toString()).toEqual('3');
      todoList[2].getText().then(function (text) {
        //Verifying newly entered TODO is added
        expect(text).toEqual('write first protractor test');
      });
    });
  });
});

We have used element, by, browser etc.. in our script. So we have imported required dependencies in first line.

Create the below config.ts file in ‘ProtractorAutomation’ folder.
config.ts

import { ProtractorBrowser, Config } from 'protractor';

export let config: Config = {
  seleniumAddress: 'http://localhost:4444/wd/hub',
  capabilities: {
    'browserName': 'chrome'
    },
  framework: 'jasmine',
  specs: ['./specs/**/*.js'],
  jasmineNodeOpts: {
    defaultTimeoutInterval: 90000
  },
  onPrepare: () => {
   let globals = require('protractor');
   let browser = globals.browser;
   browser.manage().window().maximize();
   browser.manage().timeouts().implicitlyWait(5000);
 }
}

Make sure your project and Files should look like below.
protractortypescriptstructurewithfiles

6. How to Run?

Run the below command to run selenium server.

webdriver-manager start

Open new CommandPrompt/Terminal and navigate to your project location and run the below command to run the tests.
npm test

You should see a Chrome browser window opens up and navigate to the todo list section in the AngularJS page, then close itself (this should be very fast!).
The test output should be 1 test, 0 failures. Congratulations, you’ve run your first Protractor test!

  • Alina Cheriomushka

    I have problem. After npm test, i have error with import.
    import { ElementFinder, browser, by, element } from ‘protractor’;
    ^^^^^^
    SyntaxError: Unexpected token import

    In which way i can to fix this error?
    https://uploads.disquscdn.com/images/cf05969c3a244743d250b4eeb7459e25cd5bb464ee08c0e65d3e0b79c5908113.png

    • Vijay Daram

      Hi Alina,

      Your config.ts file is pointing to FirstSpec.ts. Please update your config config file to run ConvertedJSFiles/spec/FirstSpec.js.

      Exact line in your config.ts file should be like below.
      specs: [‘./spec/FirstSpec.js’],

%d bloggers like this: