量角器茉莉花测试中的异步代码执行

时间:2019-01-25 10:40:49

标签: javascript typescript

我有下面的茉莉花测试用例,我想将函数getAllUsageCategoriesDropListElements返回的值存储到一个数组中,这样我就可以访问测试用例中的数组并用另一个数组评估它的内容。

it('Validate the Usage Category droplist values matches with the Usage Categories Table',() => {

    let allUsageCategoryDropListElements: string[] =  [];

    additionalCostsPage.getAllUsageCategoriesDropListElements(
        element => {
            console.log("Text from the usage Cateory Droplist elements " + element);
            allUsageCategoryDropListElements.push(element);
            console.log(" from inside " + allUsageCategoryDropListElements.length);
        }
    );

    console.log("Size of the array is " +allUsagCategoryDropListElements.length );

});

方法如下:

getAllUsageCategoriesDropListElements(evaluationFunc:(element:string)=> void):void {

    E2EUtil.click(this.addAdditionalCostDialogue.usageCategoryField);

    E2EUtil.waitFor(this.addAdditionalCostDialogue.usageCategoryDropListContainer);

    browser.sleep(2000);

    var usageCategoryFromPage: string[] =  [];

    element.all(by.xpath("//*[@id='usageCategory']/div/div[3]/div/ul/li[*]/span"))

        .each(function (element, index) {

            element.getText().then(function (text){
                // console.log("text extracted is " + text);
                usageCategoryFromPage.push(text);
            })
        })

        .then(function(){
            usageCategoryFromPage.forEach(evaluationFunc);
        });
}

函数内部打印的数组大小适当增加,但在函数外部打印时为0。我认为这是由于异步代码执行所致。有人可以帮忙吗?我对这个打字稿世界很陌生。

1 个答案:

答案 0 :(得分:0)

要等待运行代码,您需要正确添加TZasync关键字。试试:

await

编辑:您的it('Validate the Usage Category droplist values matches with the Usage Categories Table', async () => { let allUsageCategoryDropListElements: string[] = []; await additionalCostsPage.getAllUsageCategoriesDropListElements( element => { console.log("Text from the usage Cateory Droplist elements " + element); allUsageCategoryDropListElements.push(element); console.log(" from inside " + allUsageCategoryDropListElements.length); } ); console.log("Size of the array is " +allUsagCategoryDropListElements.length ); }); 不是异步的,但是您使用的是Promise。您可以对其进行更新以使其异步,然后调用函数中的getAllUsageCategoriesDropListElements将正常工作。

尝试:

await/async