Beginning selenium web-driver with TypeScript - a simple guide

Currently, I am embarking on a UI Automation project utilizing Selenium and typeScript. I would greatly appreciate any insights on how to proceed with this endeavor. My previous experience involves working with Selenium WebDriver in Java. I have successfully installed nodejs and npm on my local machine.

Answer №1

To get started:

  1. Start by downloading Chromedriver and adding it to PATH
  2. Clone this repository and navigate to MochaTypescriptTest-101/
  3. Run npm install
  4. Execute mocha test\SeleniumDemo.test.js

While this may not be exactly what you are seeking, it includes tests that can help you begin with selenium and typescript. Study their configuration for a smooth start. For more information, refer to this link which provides detailed tests like the ones listed below:

before – sets up chrome driver

before(function () {
    // setting up chrome driver 
    driver = new webdriver.Builder() 
    .withCapabilities(webdriver.Capabilities.chrome()) 
    .build();

    // maximizing chrome browser 
    driver.manage().window().maximize(); 
});

afterEach – captures screenshot on test failure, gathers logs etc

afterEach(function () {
    let testCaseName: string = this.currentTest.title; 
    let testCaseStatus: string = this.currentTest.state; 

    if (testCaseStatus === 'failed') { 
        console.log(`Test: ${testCaseName}, Status: Failed!`);

        // taking screenshot when test fails 
        driver.takeScreenshot().then((data) => { 
            let screenshotPath = `TestResults/Screenshots/${testCaseName}.png`; 
            console.log(`Saving Screenshot as: ${screenshotPath}`); 
            fs.writeFileSync(screenshotPath, data, 'base64'); 
        }); 
     } else if (testCaseStatus === 'passed') { 
         console.log(`Test: ${testCaseName}, Status: Passed!`); 
     } else { 
         console.log(`Test: ${testCaseName}, Status: Unknown!`); 
    } 
});

after – closes the browser

after(function () {
    driver.quit();
});

it – executes test operation and verifies result. e.g. open bing.com and search for a text

it('should search for nilay shah at bing.com', function () {
     let Url: string = `http://www.bing.com`;
     return driver.get(Url).then(function () {
     console.log(`Page "${Url}" opened`);
     }).then(() => {
         return driver.getCurrentUrl().then((currentUrl) => {
             currentUrl.should.include(
             `www.bing.com`,
             `Expected url: www.bing.com, Actual url: ${currentUrl}`);
         }).then(() => {
             let searchBox = driver.findElement(webdriver.By.name('q'));
             searchBox.sendKeys('nilay shah');
             return searchBox.getAttribute('value').then((value) => {
                 value.should.equal('nilay shah');
             });
          });
      });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Python Selenium package encountering formatting issues

Currently on Linux Debian 9 and using PyCharm for web scraping with Python 3.5 as interpreter. This is the script being used: from selenium import webdriver import time import datetime from selenium.webdriver.common.keys import Keys Everything works fin ...

Retrieving data from array services in Angular using Typescript

I need help retrieving data from an array in my services using a get function. I've tried using the .filter and .find functions, but I'm struggling with the execution and haven't been able to retrieve the data successfully. I know this may b ...

Automation tests can yield varying results across different browsers

I am facing a challenge with my automation tests, as they need to be executed in both Chrome desktop edition and Chrome mobile edition. One specific test requires the desktop version to click on an element that appears only when hovered over, while the m ...

Guide to Logging into Jmeter with a Java Script Popup

Can you provide detailed instructions on how to log in using Jmeter with a Java script Popup that opens upon clicking a button? I need guidance on the step-by-step process of logging into a website for Load Testing purposes. https://i.sstatic.net/r2e7p.pn ...

How to effectively handle null in Typescript when accessing types with index signatures unsafely

Why am I getting an error that test might be potentially undefined even though I've enabled strictNullCheck in my tsconfig.json file? (I'm unsure of the keys beforehand) const a: Record<string, {value: string}> = {} a["test"].va ...

Receiving errors in React/TS/material-ui when attempting to use a variable as a value for a grid property. Messages include "No overload matches" and "Type 'number' is not assignable to type..."

tl;dr: When using a variable as the value of a grid xs property in JSX, material-ui throws a TS error. I'm working on implementing grids in material-ui with React/TypeScript. The goal is to make the width of a specific element dependent on the quant ...

Is it possible to compile a TypeScript file with webpack independently of a Vue application?

In my Vue 3 + Typescript app, using `npm run build` compiles the app into the `dist` folder for deployment. I have a web worker typescript file that I want to compile separately so it ends up in the root of the `dist` folder as `worker.js`. Here's wha ...

What is the proper way to incorporate the "pdf" package into a TypeScript project?

I recently installed pdf and its types using the following command: npm install --save pdf @types/pdf However, I am struggling to find any documentation on how to actually use this package. When I try the following code: import {PDFJS} from 'pdf&ap ...

Managing authentication in website testing can prove to be a challenge, especially when dealing with Google

I am in the process of developing a website that utilizes Google OAuth for user authentication and to execute various actions within Google services (such as sending emails, creating calendar events, etc.) on behalf of the user. My goal is to use selenium ...

Using Typescript for-loop to extract information from a JSON array

I'm currently developing a project in Angular 8 that involves utilizing an API with a JSON Array. Here is a snippet of the data: "success":true, "data":{ "summary":{ "total":606, "confirmedCasesIndian":563, "con ...

The process of dynamically adding a property to the parameter of the React setState method

In my project, I utilize reactjs and typescript. Here are the lines of code I am using: if (reinitGridState) { this.setState({ isbusy: false, itemsList: data, colList: columns, gridState: this.initGridState, gri ...

What is the syntax for passing a generic type to an anonymous function in a TypeScript TSX file?

The issue lies with the function below, which is causing a failure within a .tsx file: export const enhanceComponent = <T>(Component: React.ComponentType<T>) => (props: any) => ( <customContext.Consumer> {addCustomData => ...

Tips for resolving the 'float' type object without length error when using Python and Selenium to automate web form filling

I am currently working on automating a form filling process using Selenium. I have successfully imported Selenium and my code runs without issue on the first iteration. However, when attempting to run it for the second time, I encounter the following error ...

Instructions for transferring profile with saved login details to Selenium and enabling automated login process:

I am attempting to transfer my saved Chrome profile to utilize with chromedriver. The goal is to access the stored login details in that profile and automatically sign in to Facebook using selenium. Here is the code I am currently using: from selenium.web ...

Choosing a frameset by its index in Selenium using Python

I am currently in the process of learning how to use Selenium with Python. Here is the code I am attempting to run: browser=webdriver.Firefox() browser.maximize_window() browser.get('https://netbanking.hdfcbank.com') #print browser.page_source ...

Angular 5 is throwing an error stating that it cannot read the property 'text' of undefined

I have developed a question component where I have added some predefined questions. However, when I attempt to execute the application, it displays 'undefined' text. Below is my component code: import { Component, OnInit } from '@angular/c ...

Having trouble getting elastic-apm-node to function with Webpack, Typescript, and ES6?

While working with a TypeScript setup using webpack and babel, I encountered an issue when trying to include elastic-apm-node. Despite having the settings in environment variables, I still faced errors. import * as apm from 'elastic-apm-node/start&ap ...

Tips for avoiding multiple reference paths in Angular TypeScript: - Simplify your imports

Setting up Typescript for an Angular 1.5 application has been a bit of a challenge. To ensure that a TS file can be compiled by gulp without any errors, I have to include the following line: ///<reference path="../../../../typings/angularjs/angular.d.t ...

Encountering difficulties while utilizing Ramda in typescript with compose

When attempting to utilize Ramda with TypeScript, I encountered a type problem, particularly when using compose. Here are the required dependencies: "devDependencies": { "@types/ramda": "^0.25.21", "typescript": "^2.8.1", }, "dependencies": { "ramda ...

It appears that tsc is failing to recognize the "exclude" directives specified in the tsconfig.json file

I'm having difficulty with tsc recognizing my tsconfig.json file and compiling my .ts files. I keep encountering duplication errors that I'm trying to prevent using my tsconfig.json. Here's what I have: package.json tsconfig.json typings.j ...