首页 > 解决方案 > 如何使量角器 JavaScript 等待读取文件完成?

问题描述

我将测试的应用程序 URL 放在一个文本文件中,因此我希望 Protactor 执行等待而不使用“Sleep()”方法,直到它完成读取,以便 Protactor 可以使用文件中的文本启动浏览器到网站。但到目前为止,Protractor 执行速度非常快,因此无法从文件中获取文本,因此无法在 Chrome 上打开网站

function retrieveAppURL(){
    const fs = require('fs')
    var data = null;

    fs.readFile("appURL.txt", (err, text) => {
        if (err){
            console.log("error " + err);
        }
        else
        {
            console.log("text file data = " + text.toString());
            data = text.toString();
        }
    });

    return data;
}

function launchAppURL(){
        var data = retrieveAppURL();

        browser.get(data );
        browser.waitForAngularEnabled(false);
    } catch (err) {
        console.log("exception " + err.message);    
    }
}

标签: javascriptprotractor

解决方案


您可以使用 browser.wait() 来等待文件像这样读取。

await browser.wait(async function () {
    return fs.readFile("appURL.txt", (err, text) => {
        if (err){
            console.log("error " + err);
        }
        else
        {
            console.log("text file data = " + text.toString());
            data = text.toString();
        }
    });
}, 30*1000, "File has not been read within 30 seconds")

推荐阅读