量角器测试不等待文件下载

时间:2019-04-01 03:00:20

标签: javascript protractor

我正在测试,当下载Excel文件时,它应该验证文件中的数据。我有这两个规格:

it('should be able to download the excel file of the student data', async function(){

    expect( homePage.ExcelFieDownloaded()).toBe(true);

});

it('Should match total records in Excel File with the data table', async function(){

    expect (await regDBPage.NumberOfRecordsinExcelFile()).toBe(await regDBPage.getCountofRecordsinDatabase(await regDBPage.userName())+1)

});

和excel文件的下载+读取方法是:

this.ExcelFieDownloaded = async function(){

    var today = new Date(),
        timeStamp = moment(today).format('MMDDYYYY');
    let file = './downloaded-files/StudentList'+timeStamp+'.xlsx';
    let Worksheet = 'StudentList'+timeStamp+'.pdf';
    let XL = require('exceljs');
    let Workbook = new XL.Workbook();

    let RowLength= 0;

    if(fs.existsSync(file)){
        fs.unlinkSync(file);
    }else{
        console.log('There is no pre-existing .xlsx file in the directory ');
    }

    await sync.waitUntilElementClickable(locator.ExcelButton, 5000);
    await locator.ExcelButton.click();
    let file_found = await fs.existsSync(file);
    return (await file_found)

};

 this.NumberOfRecordsinExcelFile = async function(){
    const filePath ='./downloaded-files/StudentList'+timeStamp+'.xlsx';

    try{
        let excelFile = await filePath;

        await fs.existsSync(excelFile);

        let WB = await Workbook.xlsx.readFile(await excelFile);
        let WS = await WB.getWorksheet(1);
        let RC = await WS.actualRowCount;
        console.log('Number of actual data in excel file: ' + RC);
        return await RC
    } catch (err) {
        console.log(err);
    }

}

如果在测试开始时文件夹中已经存在所需的excel文件,并且我在第一个规范中禁用了取消链接,则测试可以顺利通过。但是,如果文件夹中没有此类文件,并且第二个规范必须等待第一个规范下载该文件,或者如果在第一个规范中激活了取消链接功能,它将不等待并返回以下内容:

  

。错误:找不到文件:./downloaded-files/StudentList03312019.xlsx       在C:\ ProtractorTests \ node_modules \ exceljs \ lib \ xlsx \ xlsx.js:60:17

看起来异步等待不适用于第二个规范。如何使规范在执行文件之前等待文件生成?

1 个答案:

答案 0 :(得分:1)

await fs.existsSync(excelFile);仅在等待fs.existsSync函数完成(如果文件确实存在,则返回true),而不是实际上在等待文件存在。

您可以尝试添加browser.wait(),这样将等待文件下载。

await browser.wait(async function () {
    return await fs.existsSync(excelFile);
}, 30*1000, "File has not downloaded within 30 seconds")
相关问题