Reputation: 872
I am testing that when as Excel file is downloaded, it should validate the data in the file. I have these two specs :
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)
});
and the excel file download + read methods are :
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);
}
}
If the desired excel file already exists in the folder at the beginning of the test and I disable the unlink in the first spec, then the tests pass without any problem. But if there is no such file in the folder and the 2nd spec have to wait for the first spec to download the file, or if the unlink function is activated in the first spec, it does not wait and returns the following :
.Error: File not found: ./downloaded-files/StudentList03312019.xlsx at C:\ProtractorTests\node_modules\exceljs\lib\xlsx\xlsx.js:60:17
It looks like the async await is not working for the 2nd spec. How can I make the spec to wait for the file to be generated before executing it?
Upvotes: 0
Views: 1719
Reputation: 2348
await fs.existsSync(excelFile);
is only waiting for the fs.existsSync function to complete (which returns true if the file does exist), not actually waiting for the file to exist.
You could try adding a browser.wait() which would wait the file to download like so.
await browser.wait(async function () {
return await fs.existsSync(excelFile);
}, 30*1000, "File has not downloaded within 30 seconds")
Upvotes: 1