是否可以在 'executeScript' 内解决 promise?

Is it possible to resolve promise within the 'executeScript'?

我正在尝试使用 Protractor+Jasmine 为我的非 Angular 应用程序编写我的第一个测试。

我需要调用我的应用程序全局实例的 API 函数,获取结果并在测试中进行比较。此函数的传入参数之一是回调,一旦数据准备就绪就会调用该回调。此功能的执行时间取决于应用程序的配置。

我试图在这个回调函数中解析 promise 对象并在测试中处理它。这是我的代码的简化版本,它也不起作用。看起来脚本 arguments[0].fulfill("Some data"); 从未执行过,因为测试因超时而失败并显示消息:

timed out after 10000msec waiting for spec to complete

describe('Text', function() {
    it('should be displayed on stage with set value', function() {
        var deferred = protractor.promise.defer();
        var promise = deferred.promise;

        promise.then(function (data) {
            console.log(data);
        });

        browser.driver.executeScript('arguments[0].fulfill("Some data");', deferred);
    });
});

是否有可能在函数 executeScript() 的上下文中解析(实现)promise 对象?还有其他方法可以解决这个问题吗?

UPD: 这段代码对我有用。谢谢!

describe('Text', function() {
    it('should be displayed on stage with set value', function() {
        var deferred = protractor.promise.defer();

        browser.driver.executeAsyncScript(function () {
            var callback = arguments[arguments.length - 1];

            MyApp.apiFunction({
                callback: function (callbackParams) {
                    callback(callbackParams);
                }
            });
        }, function (data) { // Callback
            deferred.fulfill(data);
        }).then(function (result) {
            // Do what you need with data...
            console.log('Result: ', result);
        });
    });
});

Jasmine 有一个名为 done 的异步resole 所以如果你将它作为延迟传递而不是我认为它应该有效

 it('should be displayed on stage with set value', function(done) {
 browser.driver.executeScript('arguments[0].fulfill("Some data");', function()

    {
 Object.defineProperty(this, "promise", {
          get: function () { done() },
          enumerable: true
      });


done()
});

executeAsyncScript()正是您所需要的。

引用@hankduan 的话题:

use executeAsyncScript when you care about a return value in a calling script, but that return value won't be available immediately. This is especially necessary if you can't poll for the result, but must get the result using a callback or promise (which you must translate to callback yourself).