Reputation: 229
I created test that:
cypress/download
TEST.pdf
TEST: `
it.only("should downloads file", () => {
cy.task('deleteDirectory', downloadsFolder); // deleting download directory
cy.get("downloadButton").click(); // downloading 'TEST.pdf' file
cy.task('isExistDownloadedFile', 'TEST.pdf').should('equal', true); // assertion
cy.task('deleteDirectory', downloadsFolder); // deleting download directory
})
`
plugins/index.js `
**--snip--**
const path = require('path');
const fs = require('fs');
const downloadDirectory = path.join(__dirname, '..', 'downloads');
const findDownloadedFile = (filename) => {
**const FileName = `${downloadDirectory}/${filename}`;**
const contents = fs.existsSync(FileName);
return contents;
};
const hasFile = (filename, ms) => {
const delay = 10;
return new Promise((resolve, reject) => {
if (ms < 0) {
return reject(
new Error(`Could not find any file ${downloadDirectory}/${filename}`)
);
}
const found = findDownloadedFile(filename);
if (found) {
return resolve(true);
}
setTimeout(() => {
hasFile(filename, ms - delay).then(resolve, reject);
}, delay);
});
};
**--snip--**
// find downloaded file and match the name of that file with the expected filename
on('task', {
isExistDownloadedFile(filename, ms = 4000) {
return hasFile(filename, ms);
},
});
return config;
`
My question:
Now I can assert only entire file name e.g.
TEST.pdf (downloaded) equal to TEST.pdf (expected)
RESULT: PASSED
but how can I make that my program will also accept some characters, like only extension for instance:
TEST.pdf (downloaded) contains .pdf (expected)
RESULT: PASSED
Upvotes: 2
Views: 1146
Reputation: 31954
Install glob and use it in place of fs.existsSync()
plugins/index.js
...
const glob = require("glob");
const findDownloadedFile = (filename) => {
const matches = glob.sync(fileName);
return (matches.length > 0);
}
test
// partial name
cy.task('isExistDownloadedFile', '*.pdf').should('equal', true)
// still works with full name
cy.task('isExistDownloadedFile', 'TEST.pdf').should('equal', true)
Upvotes: 3
Reputation: 7135
You could implement something like this answer to filter the results of the entire list of files in the directory.
const findDownloadedFile = (filename) => {
const files = fs.readDirSync(downloadDirectory).filter((x) => x.includes(filename));
return files.length
};
Upvotes: 1