量角器中ajax请求的一般解决方案

时间:2018-02-06 07:16:16

标签: ajax async-await protractor

我想等到ajax调用完成。下面我写了一般方法。但似乎这不起作用。

当我每次afterajax请求运行调用函数时,isLoaded总是为真。

在量角器中,有什么解决方案吗?或者我在哪里弄错了?

谢谢

    module.waitUntilJqueryLoad = async function (timeout) {
    var isDone = false;

    timeout = timeout || 60;

    await browser.sleep(1000);
    //Wait for jQuery to load
    var isLoaded = await browser.driver.executeScript("return jQuery.active == 0;");

    if(isLoaded) {
        console.log("JQuery is Ready!");

        return await browser;
    }

    //This loop will rotate for 60 times to check If page Is ready after every 1 second.
    //You can replace your value with 60 If you wants to Increase or decrease wait time.
    for (var i = 0; i < timeout; i++) {
        try {
            await browser.sleep(1000);
        } catch (err) {}

        //To check page ready state.
        var isLoaded = await browser.driver.executeScript("return jQuery.active == 0;");
        console.log(isLoaded);

        if(isLoaded) {
            console.log("JQuery is Ready");
            isDone = true;
        } else {
            console.log("JQuery is NOT Ready !!");
        }

        if(isDone)
            break;
    }

    return browser;
};

1 个答案:

答案 0 :(得分:1)

我有一个解决方法。如果您的加载弹出窗口添加了显示样式,它将起作用。

这不是一般解决方案,但其他已发布的解决方案甚至无法在代码下工作。

await browser.wait(until.invisibilityOf(element(by.id('loadingPanel'))), 60000);

示例用法:

element(by.id('selectPerson')).waitForInvisibilityOf(10000); // wait 10 seconds

这是我的解决方案;

protractor.ElementFinder.prototype.waitForInvisibilityOf = async function (timeout) {
var _debug = true;
var isDone = false;
timeout = timeout || 60000;
var seconds = timeout / 1000;

if(await !this.isPresent())
    return this;

//This loop will rotate for 60 times to check If page Is ready after every 1 second.
//You can replace your value with 60 If you wants to Increase or decrease wait time.
for (var i = 1; i <= seconds; i++) {
    await browser.sleep(1000);

    var style = await this.getAttribute('style');
    var insibilityOf = await style.includes('display: none;');
    var visibilityOf = await style.includes('display: block;');

    if(insibilityOf) {
        if(_debug)
            console.log(i + " second: Element invisible!");
        isDone = true;
    }
    else {
        if(_debug)
            console.log(i + " second: Element NOT invisible!");
    }

    if(seconds === i)
        throw "Element invisibility timed out after "+ timeout +" milliseconds";

    if(!insibilityOf && !visibilityOf && i > 10) // break for paging is loaded
        break;

    if(isDone) // If element is invisible
        break;
}

return await this; };