node.js 如何在 Protractor 中创建和操作 Promise?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21055400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:37:56  来源:igfitidea点击:

How to create and manipulate promises in Protractor?

node.jsangularjsprotractor

提问by Konrad Garus

I want to use the Node Http module to call my server directly in order to set up my Protractor tests. Http is callback based and I want to turn that into promises.

我想使用 Node Http 模块直接调用我的服务器以设置我的量角器测试。Http 是基于回调的,我想把它变成承诺。

For example, I want to have this function return promise:

例如,我想让这个函数返回承诺:

function callMyApi() {
  var promise = // somehow create promise;

  http.request({path: '/yada/yada', method: 'POST'}, function(resp) {
    promise.complete(resp);
  });

  return promise;
}

So, the question is: what do I need to require()and put in place of "somehow create promise" for this to work?

所以,问题是:我需要什么来require()代替“以某种方式创造承诺”才能使其发挥作用?

回答by Jmr

Protractor uses WebDriver's promises and exposes that API globally on 'protractor'. So you should be able to do

量角器使用 WebDriver 的承诺并在“量角器”上全局公开该 API。所以你应该能够做到

var deferred = protractor.promise.defer();
return deferred.promise;

For the full WebDriverJS Promise API, see the code at https://code.google.com/p/selenium/source/browse/javascript/webdriver/promise.js

有关完整的 WebDriverJS Promise API,请参阅https://code.google.com/p/selenium/source/browse/javascript/webdriver/promise.js 上的代码

回答by mvndaai

This is the wrong way to do this, but knowing about the Protractor Control Flow could help. If you want regular Javascript run in Protractor order add it through the control flow.

这是执行此操作的错误方法,但了解量角器控制流程可能会有所帮助。如果您希望以量角器顺序运行常规 Javascript,请通过控制流添加它。

In this case you could use your own promise library if you want then just use browser.waitto wait for your promises to complete.

在这种情况下,如果您愿意,您可以使用自己的承诺库,然后仅用于browser.wait等待您的承诺完成。

var Promise = require('bluebird');
var promises = [];
browser.controlFlow().execute(function() {
    var p = new Promise...
    promises.push(p);
});
browser.wait( function(){ return Promise.all(promises); }, timeoutMs );

I use this not for regular promises, but for console.logstatements or doing timing for a part of a test, or even using fsto print something in a test to a file.

我不是将它用于常规承诺,而是用于console.log声明或为测试的一部分计时,甚至fs用于将测试中的某些内容打印到文件中。

var startTime, duration; 
browser.controlFlow().execute(function() {
    startTime = new Date().getTime();
});
//Protractor code you want timed
browser.controlFlow().execute(function() {
    duration = new Date().getTime() - startTime;
    console.log("Duration:", duration);
});