Глобальная переменная извлекает значение как [объект объекта] в транспортире - PullRequest
0 голосов
/ 18 мая 2018

Я новичок в транспортире, при создании тестового скрипта я получаю одно значение в функции 1, сохраняю его в глобальной переменной и пытаюсь использовать его в другой функции.

Получил значение в одной функции как

global.store = element(by.xpath("(//table/tbody/tr/td[@class='ng-scope'][2])[1]")).getText();   

Теперь попытался использовать то же значение в другой функции, что и

element(by.xpath("//div[contains(text(),'" +store+ "')]")).click();

Отображение ошибки как

Failed: No element found using locator: By(xpath, //div[contains(text(),'[object Object]')])[0m

Ответы [ 2 ]

0 голосов
/ 18 мая 2018
global.store = element(by.xpath("(//table/tbody/tr/td[@class='ng-scope'][2])[1]")).getText(); 

// Because all protractor API are Async and return promise, 
// instead of return the eventual value. 
// To consume the eventual value you need to do it within `then()`
// Or use `await` 

global.store.then(function(text){
   return element(by.xpath("//div[contains(text(),'" +text+ "')]")).click();
});
0 голосов
/ 18 мая 2018

Вероятно, вам следует попробовать использовать JSON.stringify()

element(by.xpath("//div[contains(text(),'" +JSON.stringify(store)+ "')]")).click();

Чтобы создать строку, представляющую объект, хранящийся в store.

let obj = {"foo":"bar"};

console.log(obj.toString()); // toString get's called when adding an object to a String in JS

console.log(JSON.stringify(obj));

Согласно комментарию OP:

Используйте пользовательскую функцию с JSON.stringify(), которая исключает циклические определения:

let obj = {"foo":"bar"};
obj.o = obj; //circular definition


let cache = [];

let text = JSON.stringify(obj, function(key, value) {
    if (typeof value === 'object' && value !== null) {
        if (cache.indexOf(value) !== -1) {
            // Circular reference found, discard key
            return;
        }
        // Store value in our collection
        cache.push(value);
    }
    return value;
});
cache = null; // Enable garbage collection

console.log(text);
Источник

Затем вы можете использовать переменную text в своем коде:

element(by.xpath("//div[contains(text(),'" +text+ "')]")).click();

Редактировать согласнокомментарий ОП:

Строка, которую вы хотите, находится в obj.parentElementArrayFinder.actionResults_.value_[0].Вот как вы получаете к нему доступ:

let obj = {"browser_":{"driver":{"flow_":{"propagateUnhandledRejections_":true,"activeQueue_":{"name_":"TaskQueue::651","tasks_":[],"interrupts_":null,"pending_":null,"subQ_":null,"state_":"new","unhandledRejections_":{}},"taskQueues_":{},"shutdownTask_":null,"hold_":{"_called":false,"_idleTimeout":2147483647,"_idlePrev":{"_timer":{},"_unrefed":false,"msecs":2147483647,"nextTick":false},"_idleStart":76744,"_repeat":2147483647,"_destroyed":false}},"session_":{"stack_":null,"parent_":null,"callbacks_":null,"state_":"fulfilled","handled_":true,"value_":"971758c120a30c6a741c31c905833dea","queue_":{"name_":"TaskQueue::26","tasks_":[],"interrupts_":null,"pending_":null,"subQ_":null,"state_":"finished","unhandledRejections_":{}}},"executor_":{"w3c":false,"customCommands_":{},"log_":{"name_":"webdriver.http.Executor","level_":null,"parent_":{"name_":"webdriver.http","level_":null,"parent_":{"name_":"webdriver","level_":null,"parent_":{"name_":"","level_":{"name_":"OFF","value_":null},"parent_":null,"handlers_":null},"handlers_":null},"handlers_":null},"handlers_":null}},"fileDetector_":null},"baseUrl":"","getPageTimeout":10000,"params":{},"resetUrl":"data:text/html,<html></html>","debugHelper":{},"ready":{"stack_":null,"parent_":null,"callbacks_":null,"state_":"fulfilled","handled_":true,"queue_":null},"trackOutstandingTimeouts_":true,"mockModules_":[{"name":"protractorBaseModule_","args":[true]}],"ExpectedConditions":{},"plugins_":{"pluginObjs":[],"assertions":{},"resultsReported":false},"allScriptsTimeout":11000,"internalRootEl":"","internalIgnoreSynchronization":true},"parentElementArrayFinder":{"locator_":{"using":"xpath","value":"(//table/tbody/tr/td[@class='ng-scope'][2])[1]"},"actionResults_":{"stack_":null,"parent_":null,"callbacks_":null,"state_":"fulfilled","handled_":false,"value_":["DLL000010"],"queue_":null}},"elementArrayFinder_":{}};

let wantedText = obj.parentElementArrayFinder.actionResults_.value_[0];

console.log(wantedText);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...