【问题标题】:jasmine print getText output outside function茉莉花打印getText在函数外输出
【发布时间】:2016-06-06 16:42:47
【问题描述】:

我正在编写一个量角器规范,它使用 angularJS 和 jasmine 从页面中获取文本,稍后我想将其从字符串转换为整数。我的第一个问题是在函数之外访问 getText 值。比如下面的代码:

var post_count = element.all(by.binding('InboxItem.Count')).get(0);
 post_count.getText().then (function (text){
 console.log('mytext_inside_function = ' + text);
 return text;
});
console.log('mytext_outside_function = ' + post_count);

我可以看到代码正在异步执行,并且 console.log 我的 text_outside_function 在 my_text_inside_function 之前运行,因此返回“对象对象”而不是数字 7(这是文本而不是数字)

ᐅ protractor protractor.conf.js --suite inbox
[10:56:34] I/local - Starting selenium standalone server...
[10:56:35] I/launcher - Running 1 instances of WebDriver  
Started
mytext_outside_function = [object Object]
mytext_inside_function = 7
.
1 spec, 0 failures
Finished in 0.938 seconds

我是 jasmine promises 的新手,不知道如何纠正这个问题。我将 .then (function... 添加到我的测试中,但似乎没有解决这个承诺。 我的最终目标是获取文本( 7 ),然后将其从当前字符串转换为数字,以便我可以对其进行计算(加法)。

编辑.... 感谢尼克的建议。我想我做错了。我添加了我认为在函数之外的 mytext 变量(可能是错误的)。见下文..

 var post_count = element.all(by.binding('InboxItem.Count')).get(0);
 var mytext = post_count.getText().then (function (text){
 console.log('mytext_inside_function = ' + text);
 return text;
 });
 console.log('mytext_outside_function = ' + my text);

我收到此错误。

mytext_outside_function = ManagedPromise::810 {[[PromiseStatus]]: "pending"}

【问题讨论】:

  • 在函数外部初始化一个变量并将结果存储在该变量中。

标签: angularjs jasmine protractor


【解决方案1】:

Promise的分辨率中调用console.log

var result = element(by.binding('InboxItem.Count')).getText().then(parseFloat);

result.then((value) => console.log("count: ", value));

或者在执行流程中推送一个新函数来显示结果:

var count = 0;
element(by.binding('InboxItem.Count')).getText().then((text) => {
  count = parseFloat(text);
});

browser.controlFlow().execute(() => {
  console.log("count: ", count);
});

【讨论】:

  • 弗洛伦特,感谢您的第一个建议成功了!谢谢大家!!
【解决方案2】:

像这样的

const defer = Promise.defer();
var count =0;

var post_count = element.all(by.binding('InboxItem.Count')).get(0);
 post_count.getText().then (function (text){
   count = parseInt(text);
   console.log('mytext_inside_function = ' + count);
   defer.resolve(count);
   return defer.promise;
});


console.log('mytext_outside_function = ' + count);

通常第二行 console.log 会在上述承诺解决之前执行。所以你会看到控制台输出为promise pending。你可以使用 const defer = Promise.defer(); defer.resolve(count);返回 defer.promise;在上述函数中。通过这样做,您正在等待承诺得到解决

【讨论】:

  • Varun 你的回答给了我“mytext_outside_function = undefined”
  • 对不起,你需要做 var count =0;在第一行,或者您可以只使用 let count;
  • Varun,你能用 Promise.defer() 作为代码示例来展示你的建议吗?我很好奇这是如何工作的。
猜你喜欢
  • 2015-05-05
  • 2014-12-12
  • 1970-01-01
  • 2015-09-29
  • 2018-02-22
  • 2013-06-29
  • 1970-01-01
  • 1970-01-01
  • 2015-07-26
相关资源
最近更新 更多