When using Protractor with Typescript, you may encounter the error message "Failed: Cannot read property 'sendKeys' of undefined"

Having trouble creating Protractor JS spec files using TypeScript? Running into an error with the converted spec files?

Error Message: Failed - calculator_1.calculator.prototype.getResult is not a function

Check out the TypeScript files below:

calculator.ts

import { element, browser, by, ExpectedConditions as EC, ElementFinder, ElementArrayFinder } from 'protractor';

export class calculator {

    firstElement = element(by.model('first'));
    secondElement = element(by.model('second'));
    submit = element(by.id('gobutton'));
    operator = element.all(by.options('value for (key, value) in operators'));

     getResult = (val1: string, val2: string, operator: string): any =>{

        this.firstElement.sendKeys(val1);
        this.secondElement.sendKeys(val2);
        // this.operator.$$("option:contains('" + operator + "')").click();

    }

}

SampleSpec.ts

 import { browser, by, until, ExpectedConditions as EC, Key, element, ElementFinder } from "protractor";

import { helperUtility as util } from '../utility/helperUtility';

import { calculator as calc } from '../pages/calculator';

beforeEach(() => {
    util.prototype.isAngular(false);
    browser.get('https://juliemr.github.io/protractor-demo/');
});


describe('Test login functionality', () => {

    xit('should login the user and allow to logout ', () => {

        var resultCountBefore = element(by.repeater('result in memory'));
        element(by.model('first')).sendKeys('3');
        element(by.model('second')).sendKeys('5');
        element(by.id('gobutton')).click();


        browser.wait(EC.or(isResultUpdated), 5000);
        browser.sleep(500);
        let result = element(by.xpath("//button[@id='gobutton']/../h2")).getText();
        expect(result).toEqual('8');


    });


    it('test mathematical operation', () => {


        browser.waitForAngular();
        calc.prototype.getResult('1','2','+');



    });


});





export let isResultUpdated = function () {

    return element(by.xpath("//button[@id='gobutton']/../h2")).getText().then(function (result) {
        console.info(result + ' is the result')
        return result == '. . . . . .';
    });


};

config.ts

import { ProtractorBrowser, Config,browser } from 'protractor';

export let config: Config = {

    allScriptsTimeout: 60000,
    baseUrl: 'https://www.google.com',
    seleniumAddress: 'http://localhost:4444/wd/hub',
    framework: 'jasmine2',
    capabilities:{
        browserName:'chrome'
    },
    jasmineNodeOpts: {
        showColors: true,
        defaultTimeoutInterval: 30000
    },
    onPrepare: () => {
        browser.manage().window().maximize();
        browser.manage().timeouts().implicitlyWait(5000);

    },specs:['../specs/First.spec.js'],

};

Error

Failures:
1) Test login functionality test mathematical operation
  Message:
    Failed: clculator_1.calculator.prototype.getResult is not a function
  Stack:
    TypeError: clculator_1.calculator.prototype.getResult is not a function
        at Object.<anonymous> (F:\Selenium2\Protractor\TypeScriptProject\ConvertedJSFiles\specs\First.spec.js:22:42)
        at C:\Users\Harsha\AppData\Roaming\npm\node_modules\protractor\node_modules\jasminewd2\index.js:102:25
        at new ManagedPromise (C:\Users\Harsha\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\
promise.js:1067:7)
        at controlFlowExecute (C:\Users\Harsha\AppData\Roaming\npm\node_modules\protractor\node_modules\jasminewd2\index.js:87:
18)
        at TaskQueue.execute_ (C:\Users\Harsha\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\
promise.js:2970:14)
        at TaskQueue.executeNext_ (C:\Users\Harsha\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\
lib\promise.js:2953:27)
        at asyncRun (C:\Users\Harsha\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js
:2860:25)
        at C:\Users\Harsha\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:676:7
        at process._tickCallback (internal/process/next_tick.js:103:7)
    From: Task: Run it("test mathematical operation") in control flow
        at Object.<anonymous> (C:\Users\Harsha\AppData\Roaming\npm\node_modules\protractor\node_modules\jasminewd2\index.js:86:
14)
        at C:\Users\Harsha\AppData\Roaming\npm\node_modules\protractor\node_modules\jasminewd2\index.js:61:7
        at ControlFlow.emit (C:\Users\Harsha\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\ev
ents.js:62:21)
        at ControlFlow.shutdown_ (C:\Users\Harsha\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\l
ib\promise.js:2565:10)

        at shutdownTask_.MicroTask (C:\Users\Harsha\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver
\lib\promise.js:2490:53)
        at MicroTask.asyncRun (C:\Users\Harsha\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\
promise.js:2619:9)
    From asynchronous test:
    Error
        at Suite.<anonymous> (F:\Selenium2\Protractor\TypeScriptProject\ConvertedJSFiles\specs\First.spec.js:20:5)
        at Object.<anonymous> (F:\Selenium2\Protractor\TypeScriptProject\ConvertedJSFiles\specs\First.spec.js:9:1)
        at Module._compile (module.js:570:32)
        at Object.Module._extensions..js (module.js:579:10)
        at Module.load (module.js:487:32)
        at tryModuleLoad (module.js:446:12)
Pending:

1) Test login functionality should login the user and allow to logout
  Temporarily disabled with xit

2 specs, 1 failure, 1 pending spec
Finished in 4.931 seconds
[22:52:57] I/launcher - 0 instance(s) of WebDriver still running
[22:52:57] I/launcher - chrome #01 failed 1 test(s)
[22:52:57] I/launcher - overall: 1 failed spec(s)
[22:52:57] E/launcher - Process exited with error code 1

Answer №1

Several issues have been identified:

  • Ensure to encapsulate your beforeEach method at the beginning of your sample spec.
  • Consider capitalizing your class name. Instead of export class calculator, opt for something like export Calculator. This recommendation aligns with style guide conventions. You can refer to the angular.io style guide for more information (personal preference).
  • Upon importing a class, remember to invoke the constructor.
  • The current baseUrl configuration in your file is set to google.com, which seems unconventional. Refer to the baseUrl documentation for clarification.
  • For a similar example involving TypeScript, Jasmine, and Protractor, you may find the cookbook useful.

Returning to your code structure:

calculator.ts

import { element, browser, by, ExpectedConditions as EC, ElementFinder, ElementArrayFinder } from 'protractor';

// A minor stylistic note
export class Calculator {
  constructor() { /* initialize calculator variables */ }

SampleSpec.ts

import { browser, by, until, ExpectedConditions as EC, Key, element, ElementFinder } from "protractor";

// The utility function is kept unchanged for now.
import { helperUtility as util } from '../utility/helperUtility';

import { Calculator } from '../pages/calculator';

// Eliminate beforeEach; it should be executed within the describe block

describe('Testing login functionality', () => {

  // Instantiate a local calculator object to be utilized in tests within this describe block
  let calculator: Calculator;

  beforeEach(() => {
    calculator = new Calculator();  // Initialize the calculator
    util.prototype.isAngular(false);
    browser.get('https://juliemr.github.io/protractor-demo/');
  });

  it('test mathematical operations', () => {
     // Omit browser.waitForAngular();
     // Angular wait is unnecessary. Review the API documentation for further insights (link provided below).
     calculator.getResult'1','2','+');
  });

Refer to the browser.waitForAngular API documentation (referenced in the it block above)

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

Utilizing getServerSideProps in the new app router (app/blah/page.tsx) for maximum functionality

I am a beginner in Next.js and I am currently experimenting with the new app router feature by placing my pages under app/.../page.tsx The code snippet provided works when using the page router (pages/blah.tsx) but encounters issues when used in app/blah/ ...

I lost my hovering tooltip due to truncating the string, how can I bring it back in Angular?

When using an angular ngx-datatable-column, I added a hovering tooltip on mouseover. However, I noticed that the strings were too long and needed to be truncated accordingly: <span>{{ (value.length>15)? (value | slice:0:15)+'..':(value) ...

What is the best way to ensure all keys of a certain type are mandatory, while still allowing for the possibility of

I am looking to create a mapping of key/value pairs for a specific type in the following way: required_key: string | undefined transformed to required_key: string | undefined (remains the same) required_key: string transformed to required_key: string (rem ...

Utilize a proxy gateway within Selenium WebDriver for enhanced browsing capabilities

My objective is to integrate a proxy gateway (such as geosurf.io) into the Selenium webdriver. I plan to achieve this using DesiredCapabilities, as it appears to be the preferred method for adding a proxy gateway according to this source. DesiredCapabi ...

Set every attribute inside a Typescript interface as non-mandatory

I have defined an interface within my software: interface Asset { id: string; internal_id: string; usage: number; } This interface is a component of another interface named Post: interface Post { asset: Asset; } In addition, there is an interfa ...

How can I extract specific data using Selenium based on dropdown selections?

Here is an example of HTML code that I have: <form action="/action_page.php"> <label for="continent">Choose Continent:</label> <select name="continent" id="continent"> <option value ...

What distinguishes selenium.selenium from selenium.webdriver?

Lately, I have been delving into working with Selenium using Python bindings. Interestingly enough, many example codes online utilize the selenium.selenium module. However, I noticed that the latest API documentation for Selenium Python Bindings 2 does not ...

Encountering a Circular JSON stringify error on Nest.js without a useful stack trace

My application is being plagued by this critical error in production: /usr/src/app/node_modules/@nestjs/common/services/console-logger.service.js:137 ? `${this.colorize('Object:', logLevel)}\n${JSON.stringify(message, (key, value ...

Clearing up confusion around identifying checkbox elements using XPath in Selenium WebDriver with Java, specifically within a

HTML code <div class="modal-footer slds-modal__footer" data-aura-rendered-by="2805:0"> <div class="rssDialogText grantAccessCheckbox packagingSetupUIRssDialogFooter" data-aura-rendered-by="2595:0" data-aura-class="packagingSetupUIRssDialogFooter" ...

Library types for TypeScript declaration merging

Is there a way to "extend" interfaces through declaration merging that were originally declared in a TypeScript library file? Specifically, I am trying to extend the HTMLCanvasElement interface from the built-in TypeScript library lib.dom. While I underst ...

Simulating chained responses in Express using JEST

I am relatively new to using jest and typescript, currently working on creating a unit test for a controller function in jest import { Request, Response } from 'express'; const healthCheck = (_req: Request, _res: Response) => { const value ...

Utilizing a single PhantomJS browser for every worker instead of generating a new instance for every URL in the queue significantly hinders speed and efficiency

Currently, my scraping process involves using Selenium's PhantomJS browser along with threading via queues and workers to handle a large number of queries. In the past, I would create a new instance of the web browser for each URL visit, as shown belo ...

Issues encountered while scraping Instagram's web content using Selenium with Python

I am facing an issue with scraping images from an Instagram profile. Even after scrolling to the bottom of the page and extracting all "a" tags, I only end up getting the last 30 image links. It seems like the driver is unable to view the full content of ...

Ways of utilizing a dynamic key for invoking a resource from prisma

Currently, I am attempting to implement a more general method to retrieve data from Prisma. The function in question appears as follows: import { Prisma, PrismaClient } from '@prisma/client'; import { NextApiRequest, NextApiResponse } from ' ...

problem encountered while attempting to drag and drop list elements on a web application utilizing dhtmlx 5.0 and wijmo grid

My web application utilizes Dhtmlx 5.0, Wijmo grid, and Typescript. One feature of the app is a dialog box that displays a list of items which can be rearranged using drag and drop functionality. This feature works without any issues on Windows PCs but enc ...

Creating a dynamic array in an Angular 2 service for real-time changes monitoring by a component

I am facing an issue where my NotificationsBellComponent is not receiving changes to the array in the service even though the _LocalStorageService is returning data correctly. Q) How can I ensure that my component receives updates when the service collect ...

Is there a way to transform a date from the format 2021-11-26T23:19:00.000+11:00 into 11/26/2021 23:19?

Having trouble formatting the date in MM/DD/YYYY HH:mm:ss format within my .ts script. I attempted to use moment.js. moment(dateToBeFormatted, "'YYYY-MM-dd'T'HH:mm:ss.SSS'Z'").format("YYYY/MM/DD HH:mm") However ...

Avoiding the use of reserved keywords as variable names in a model

I have been searching everywhere and can't find a solution to my unique issue. I am hoping someone can help me out as it would save me a lot of time and effort. The problem is that I need to use the variable name "new" in my Typescript class construct ...

What is the best way to execute an Nx executor function using Node.js?

Can a customized Nx executor function be executed after the app image is built? This is the approach I am taking: "migrate-up": { "executor": "@nx-mongo-migrate/mongo-migrate:up", "options": { &q ...

The ValidationSchema Type in ObjectSchema Seems to Be Failing

yup 0.30.0 @types/yup 0.29.14 Struggling to create a reusable type definition for a Yup validationSchema with ObjectSchema resulting in an error. Attempting to follow an example from the Yup documentation provided at: https://github.com/jquense/yup#ensur ...