Как вызвать this.function в том же файле, где мы создаем файл - PullRequest
1 голос
/ 21 марта 2019

В моем проекте мы постарались построить каркас транспортира.поэтому в js-файле мы создаем некоторые функции, используя синтаксис this.functionname, и мы хотим повторно использовать эту функцию, когда это требуется в функции, которая также присутствует в том же файле.для ясности я дал код ниже ...

это мой файл JS для многократного использования

var fb=require("H:/workspace/Protractor_PT/src/pages/FbPage.js");
var action=function(){

    beforeAll(function(){
        browser.ignoreSynchronization=true;
        browser.get("https://facebook.com");
        login();
    });

    this.clickElement=function(element){
        element.click();
    }

    this.enterText=function(element,text){
        element.sendKeys(text);
    }

    var login=function(){
        action.enterText(fb.emailField(),"dfdsfds");
        action.enterText(fb.passfield(),"dfdsfds");
    }
}
module.login=new action();

сверху, вы можете найти функции this.clickElement и this.enterText ..я хочу использовать эти функции в другой функции с именем login .. но когда я вызвал эти функции с помощью "action.enterText" - действие является основной глобальной переменной файла ... я получаю ошибку ниже

Журнал ошибок

 Message:
    Failed: action.enterText is not a function
  Stack:
    TypeError: action.enterText is not a function
        at login (H:\workspace\Protractor_PT\src\pages\Utilities.js:19:13)
        at UserContext.<anonymous> (H:\workspace\Protractor_PT\src\pages\Utilities.js:7:3)
        at C:\Users\DELL\AppData\Roaming\npm\node_modules\protractor\node_modules\jasminewd2\index.js:112:25
        at new ManagedPromise (C:\Users\DELL\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:1077:7)
        at ControlFlow.promise (C:\Users\DELL\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2505:12)
        at schedulerExecute (C:\Users\DELL\AppData\Roaming\npm\node_modules\protractor\node_modules\jasminewd2\index.js:95:18)
        at TaskQueue.execute_ (C:\Users\DELL\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:3084:14)
        at TaskQueue.executeNext_ (C:\Users\DELL\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:3067:27)
        at asyncRun (C:\Users\DELL\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:2974:25)
        at C:\Users\DELL\AppData\Roaming\npm\node_modules\protractor\node_modules\selenium-webdriver\lib\promise.js:668:7
    From: Task: Run beforeAll in control flow
        at UserContext.<anonymous> (C:\Users\DELL\AppData\Roaming\npm\node_modules\protractor\node_modules\jasminewd2\index.js:94:19)
        at Jasmine.execute (C:\Users\DELL\AppData\Roaming\npm\node_modules\protractor\node_modules\jasmine\lib\jasmine.js:200:12)
        at C:\Users\DELL\AppData\Roaming\npm\node_modules\protractor\built\frameworks\jasmine.js:132:15
        at Function.promise (C:\Users\DELL\AppData\Roaming\npm\node_modules\protractor\node_modules\q\q.js:682:9)
    From asynchronous test:
    Error
        at new action (H:\workspace\Protractor_PT\src\pages\Utilities.js:4:2)
        at Object.<anonymous> (H:\workspace\Protractor_PT\src\pages\Utilities.js:23:14)
        at Module._compile (module.js:643:30)
        at Object.Module._extensions..js (module.js:654:10)
        at Module.load (module.js:556:32)
        at tryModuleLoad (module.js:499:12)
        at Function.Module._load (module.js:491:3)
        at Module.require (module.js:587:17)
        at require (internal/module.js:11:18)

1 spec, 1 failure
Finished in 0.049 seconds

[20:22:32] I/launcher - 0 instance(s) of WebDriver still running
[20:22:32] I/launcher - chrome #01 failed 1 test(s)
[20:22:32] I/launcher - overall: 1 failed spec(s)
[20:22:32] E/launcher - Process exited with error code 1

1 Ответ

0 голосов
/ 21 марта 2019

В вашем случае, когда создаются внутренние функции, переменная action им неизвестна.Вы можете создать локальную переменную, которая указывает на родительскую функцию, и использовать ее вместо действия .

. Вы можете сделать что-то вроде этого:

var fb = require('H:/workspace/Protractor_PT/src/pages/FbPage.js')
var action = function () {
    var localAction = this;    // <<<-----------   HERE
    beforeAll(function () {
        browser.ignoreSynchronization = true
        browser.get('https://facebook.com')
        login()
    })
    this.clickElement = function (element) {
        element.click()
    }
    this.enterText = function (element, text) {
        element.sendKeys(text)
    }
    var login = function () {
        localAction.enterText(fb.emailField(), 'dfdsfds') // Use local var here.
        localAction.enterText(fb.passfield(), 'dfdsfds')
    }
}
module.login = new action()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...