The function is coming back with a value of undefined

I need some assistance with a function I have below. This function is meant to download files one by one and move them to a directory called templates. At the end, it should return the length of the directory. However, it seems to be returning an undefined value. I suspect that I am missing something here. Can anyone provide some guidance?

this.countTemplates = function () {
    var num;
    this.download_files.each( async function (elem) {
        wait.waitForElementVisibility(elem);
        js.highlighterElement(elem);
        elem.click();
        browser.driver.wait(function(){
            var filesArray = glob.sync(dirPath + '**/*.+(xlsx|docx|pptx)');
            if(typeof filesArray !== 'undefined' && filesArray.length > 0){
                return filesArray;
            }
        }, 60000).then(function(filesArray){
            var filename = filesArray[0];
            fileSystem.moveFile(filename, process.cwd()+'/templates/');
            if(fileSystem.getAllDirFiles(process.cwd()+'/templates/').length >= 6){
                num = fileSystem.getAllDirFiles(process.cwd()+'/templates/').length;
                return false;
            }

        });
    });

    return num;
}

The method getAllDirFiles() is defined as follows:

this.getAllDirFiles = function (dirPath, arrayOfFiles) {
    var files = fs.readdirSync(dirPath);

    arrayOfFiles = arrayOfFiles || [];

    files.forEach(function (file) {
        if (fs.statSync(dirPath + "/" + file).isDirectory()) {
            arrayOfFiles = getAllDirFiles(dirPath + "/" + file, arrayOfFiles);
        } else {
            arrayOfFiles.push(file);
        }
    })
    return arrayOfFiles;
}

The function currently returns an undefined value.

it('testing if templates are downloadable', () => {
var templates = bt.countTemplates();
expect(templates).toBe(6);

});

Answer №1

When utilizing async functions within each loop, it will not wait for them to finish.

Consider implementing the following solution:


this.calculateNumberOfTemplates = async function () {
    var numOfFiles;
    var tasks = this.download_files.map( async function (element) {
        wait.waitForElementVisibility(element);
        js.highlighterElement(element);
        element.click();
        return browser.driver.wait(async function(){
            var filesArray = glob.sync(dirPath + '**/*.+(xlsx|docx|pptx)');
            if(typeof filesArray !== 'undefined' && filesArray.length > 0){
                return filesArray;
            }
        }, 60000).then(function(filesArray){
            var filename = filesArray[0];
            fileSystem.moveFile(filename, process.cwd()+'/templates/');
            if(fileSystem.getAllDirFiles(process.cwd()+'/templates/').length >= 6){
                numOfFiles = fileSystem.getAllDirFiles(process.cwd()+'/templates/').length;
                return false;
            }

        });
    });
    await Promise.all(tasks)
    return numOfFiles;
}

Test the function with:

this.calculateNumberOfTemplates().then(count => {
  expect(count).toBe(6);
});

You may need to adjust according to your framework as it appears to be non-standard JavaScript.


I also noticed an issue in the code - why are you counting files in every download task?

Answer №2

An error is thrown due to a TypeError where an object is not iterable in the code snippet below:

(node:12451) UnhandledPromiseRejectionWarning: TypeError: [object Object] is not iterable
at Function.all (<anonymous>)
at BusinessTemplatesPage.no_of_templates (/home/vivek/simplifiedcredit-qa-automation/src/page-objects/business_templates.page.js:125:23)
at UserContext.it (/home/vivek/simplifiedcredit-qa-automation/src/specs/business_templates.spec.js:41:26)
at /home/vivek/simplifiedcredit-qa-automation/node_modules/jasminewd2/index.js:112:25
at new ManagedPromise (/home/vivek/simplifiedcredit-qa-automation/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:1077:7)
at ControlFlow.promise (/home/vivek/simplifiedcredit-qa-automation/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:2505:12)
at schedulerExecute (/home/vivek/simplifiedcredit-qa-automation/node_modules/jasminewd2/index.js:95:18)
at TaskQueue.execute_ (/home/vivek/simplifiedcredit-qa-automation/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:3084:14)
at TaskQueue.executeNext_ (/home/vivek/simplifiedcredit-qa-automation/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:3067:27)
at asyncRun (/home/vivek/simplifiedcredit-qa-automation/node_modules/protractor/node_modules/selenium-webdriver/lib/promise.js:2974:25)

This error occurs when not counting, resulting in an unexpected outcome as shown below:

- Expected 1 to be 6.
- Expected 2 to be 6.
- Expected 3 to be 6.
- Expected 3 to be 6.
- Expected 5 to be 6.

The same function needs to be used to test templates of various categories, with each category containing a different number of templates.

Answer №3

this.download_files represents a collection of elements.

this.download_files = element.all(by.xpath('//button//img[@src="url_here"]'));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Schema for Monogo Database

My goal was to have a property that could give me the timestamp of when a specific task was created. I decided to add a timestamp property and set it to true, but now my code won't compile. The code is functioning perfectly fine without the timestamp ...

Deactivate the button upon click using alternative methods besides the disable attribute

I am trying to implement functionality with 3 buttons: 'click me', 'disable', and 'enable'. When the 'click me' button is clicked, it triggers an alert. However, when the 'disable' button is clicked, it sho ...

Unable to retrieve information from the wiki API

Here is the link to my codepen project: https://codepen.io/mlestina/pen/OZpOQW?editors=1111 I am having trouble retrieving data from the Wiki API. When I check the Contr-Shift-J readout, I see: Loading failed for the <script> with source “https: ...

Tips for Developing Drag Attribute Directive in Angular 2.0

Currently, I am referencing the Angular documentation to create an attribute directive for drag functionality. However, it seems that the ondrag event is not functioning as expected. Interestingly, the mouseenter and mouseleave events are working fine ac ...

How can we develop a strategy to select products based on specific features while keeping costs minimized?

I've got a collection of products with varying costs and features. Each product offers a unique set of features. I'm in need of an algorithm that, when given the specific features I desire, can recommend the most cost-effective combination of pr ...

The basic Node.js API for greeting the world encountered a connection failure

I'm currently working on setting up a basic hello world route using nodejs and express. After running node index.js, I see listening on port 3000 in the console, but when I attempt to access http://localhost:3000/helloworld, it just keeps trying to co ...

Exploring Navigation in AngularJS with ui-router

I've encountered an issue with ui-router functionality in my code. Here's a breakdown of the problem: Within my index.html file <li> <a ui-sref="day2">Day 2</a> </li> <li><a ui-sref="day3">Day 3</a& ...

When employing Flatlist, an issue arises where the image fails to appear on the screen, accompanied by an error message stating "value for uri cannot be cast from Double to String."

I'm facing an issue with displaying images in my flatlist. The error message I receive is "Error while updating property 'src' of a view managed by : RTCImageView." Can anyone help me identify what might be causing this problem in my code? ...

Determine whether a specific property value within an array, which is nested within an object, actually exists using Javascript

I am attempting to verify the existence of a property in the given object: var objects = { '1': [ 'A-TheA', 'B-TheB' ], '2': [ 'A-TheA', 'B-TheB' ] } I am seeking to confirm whether &apo ...

Dynamically Remove One Form from a Django Formset

I have been using the following code to dynamically add a form to my formset: .html {{ form2.management_form }} <div id="form_set"> {% for form2 in form2.forms %} <table class="table table2" width=100%> ...

Cloning a file input does not retain the uploaded file in the cloned input. Only the original input retains the uploaded file

Whenever I duplicate an input type file, I encounter an issue where the uploaded file from the duplicated input is also linked to the original input. It seems like the duplicate input is somehow connected to and taking files for the original one. This is ...

Is there a way to enable scrolling on the page upon loading, without moving the embedded PDF object itself?

After embedding a PDF object on my webpage, I noticed that when loading the page and scrolling using the mouse wheel, it actually scrolls up and down inside the PDF instead of moving through the entire page. To fix this issue, I have to first click in a bl ...

What are the steps to design a versatile gallery page that can serve various projects?

Allow me to get straight to the point. What is my goal? I am aiming to develop galleries for various projects. Each project's thumbnail on the main page should open a gallery as a new page. These galleries will all have the same layout but different ...

The AJAX request I'm making is not behaving as I anticipated when returning JSON data

I'm currently working on building an ajax call to compare my database and automatically update a div if any changes are detected. JavaScript is still quite new to me, especially when it comes to dealing with JSON data. I suspect the issue lies in ho ...

Trigger a function on q-select change using onChange event (Quasar Framework)

I'm trying to get the function to run when I change the selected value, but it's not working. How can I solve this issue? Below is the code I am using: <q-select v-model="single" :options="['def', 'abc', ...

Testing an HTTP error Observable with Jasmine and RxJS simulations

I encountered a similar issue, but due to commenting constraints on other questions, I had to create a new one. The problem lies in a jasmine test where a function is expected to manage an error from a service call. The service call returns an RxJS `Observ ...

"Header background image gradually fades out and disappears as you scroll, revealing a bottom gradient effect in a React application

When I scroll, my header image fades away. I used JavaScript in my React app to achieve this effect: useEffect(() => { const handleScroll = () => { if (parallaxDiv.current) { parallaxDiv.current.style.backgroundPositionY = `${ ...

Is it possible to manually activate a dropdown event using pure JavaScript?

I am attempting to manually trigger a dropdown event using JavaScript. Below is the function where I am trying to achieve this. I have successfully halted the initial event that occurs and now I need to initiate a dropdown event. stopNavigationTriggerDrop ...

Can you explain what is meant by an "out of DOM" element?

I'm feeling a bit lost when it comes to DOM nodes and all the terminology surrounding them. Initially, I believed that the DOM consisted solely of what I could see in my inspector - nothing more, nothing less. However, I've come across functions ...

Deleting an List Item from an Unordered List using Angular

Within my MVC controller, I have an unordered list with a button on each item that allows the user to remove it from the list. The issue I'm facing is that while the row is deleted from the database, it still remains visible on the screen. This is ho ...