selenium - Protractor+Typescript => 获取 "Failed: Cannot read property ' sendKeys' of undefined"

标签 selenium typescript protractor automated-tests

我正在尝试使用类型脚本创建 Protractor js 规范文件,但在运行转换后的规范文件时遇到以下错误。

失败:clculator_1.calculator.prototype.getResult 不是函数

下面是类型脚本文件。

计算器.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();

    }



}

示例规范.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/clculator';

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 mathemetical 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 == '. . . . . .';
    });


};

配置.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'],

};

错误

Failures:
1) Test login functionality test mathemetical 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 mathemetical 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

最佳答案

有几个问题:

  • 您应该将 beforeEach 方法包装在示例规范的顶部。
  • 我建议利用你的类(class)。因此,不是export class calculator,而是export Calculator。这个建议更多的是为了遵守风格指南。我喜欢 angular.io style guide (有偏见的意见)
  • 导入类后,需要调用构造函数。
  • 在您的配置文件中,您将 baseUrl 设置为 google.com。这很奇怪。请阅读docs on baseUrl
  • 对于与 typescript/jasmine/protractor 非常相似的示例,请参阅 cookbook .

回到你的代码:

计算器.ts

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

// style nit
export class Calculator {
  constructor() { /* initialize calculator variables */ }

示例规范.ts

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

// don't know what util is doing, but leaving it alone.
import { helperUtility as util } from '../utility/helperUtility';

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

// remove beforeEach, this should happen in the describe block

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

  // create a local calculator object to be used by 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 mathemetical operation', () => {
     // remove browser.waitForAngular();
     // wait for angular is not needed. Please read the api docs (link below).
     calculator.getResult'1','2','+');
  });

阅读browser.waitForAngular API docs (在上面的 it block 中提到)

关于selenium - Protractor+Typescript => 获取 "Failed: Cannot read property ' sendKeys' of undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41790118/

相关文章:

ios - NativeScript iOS 发布 : Error ITMS-90096 "not optimized for iPhone 5

typescript - webpack 编译在新计算机上出现 ts-loader 错误

selenium - 当预期消息多于一行时, Protractor ExpectedConditions.textToBePresentInElement 返回 false

javascript - 有条件地解决 promise

protractor - 断言错误: expected [ true ] to be true

javascript - 尝试在 WebdriverIO 中断言 getText 时出错

selenium - 找不到正确的Xpath

typescript - 是否可以在 typescript 中没有明确定义的情况下创建嵌套泛型

python - Selenium 中的单例实现 [Python]

selenium - Selenium 中的 Action 和 Actions 有什么区别?