Issue with running Mocha's dynamic test generation inside a before block

I followed the advice in this post to create dynamic tests, but I am encountering an issue where the actual test (test.getMochaTest() in my implementation below) is not being executed. It seems like the call on test.getMochaTest() is not getting executed in the before block.

describe('Dynamic Tests for Mocha', async () => {
    let outcome ;
    before(async() => {
        await init().catch(() => console.error('Puppeteer environment initialization failed'));
        return collectTests().then(async(collectTests) => {
            console.info('4.Executing tests :');
            describe('Dynamic test execution', async() => {
                collectTests.forEach(async(test) => {
                    console.info(`\tModule under test : ${test.name}`);

        // impl. of test.getMochaTest() DOES NOT get executed. 

                    it(test.name, async() => outcome = await test.getMochaTest().catch(async () => {
                        console.error(`error while executing test:\t${test.name}`);
                    }));
                });
            }) ;
        });
    });

    after(async () => {
        console.info('5. Exiting tests...');
        await HelperUtils.delay(10000).then(async () => { await browser.close(); });
        console.log('executing after block');
    });

    it('placeholder',  async() =>  {
        await
        console.log('place holder hack - skip it');
    });

});

An array of tests is generated here :

async function collectTests():Promise<Array<ITest>> {
    console.info('3.Collecting tests to execute ...');
    testArray = new Array<ITest>();
    const login:ITest = new SLogin('Login Check');
    testArray.push(login);
    
    return testArray;
}

The implementation of getMochaTest in SLogin below does not seem to be executed properly.

export default class SLogin extends BTest implements ITest {
    constructor(name: string) {
        super(name);
    }
    async getMochaTest():Promise<Mocha.Func> {
        return async () => {
            console.log('Running Login check');
            expect(true).to.equal(true);
        };
    }
}

Answer №1

Seems like the test is not being executed properly.

Merely calling test.getMochaTest() will only provide the async test function within a Promise, without actually running it. Hence, your catch block is capturing errors while fetching the function, not during its actual execution.

Expanding the code across multiple lines aims to clarify the process:

This snippet demonstrates what happens in your current code. Note that the test function is never invoked:

it(test.name, async () => {
    const testFn = await test.getMochaTest().catch(() => 
        console.error(`error while ***obtaining*** test: \t${test.name}`));

    // Whoops - the testFn remains untouched!
});

Below is a revised version where the test is indeed executed:

it(test.name, async () => {
    const testFn = await test.getMochaTest().catch(() => 
        console.error(`error while ***obtaining*** test: \t${test.name}`));

    const outcome = await testFn().catch(() => 
        console.error(`error while ***executing*** test: \t${test.name}`));
});

Note: The use of await and catch() align with your existing code structure. However, for better practice, consider employing a try/catch block when combining async/await with Promises.

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

Menu design with child element creatively integrated into parent element

For my mobile project, I am working on creating a window blind effect menu. The process is quite simple: Clicking on the menu icon moves the bar to the top while the menu drops down Upon selecting an item, the menu smoothly "rolls" up in a window blind s ...

Tips for typing a narrow JSX.Element

Is there a way to create a variable in React that can be either a component or a string? Like this: function MyComponent(): JSX.Element { let icon: JSX.Element | string = "/example.png"; return <div>{typeof icon === "JSX.Element" ? icon : <i ...

Issue Resolved: Struggling with PayPal's REST API

I've been working on a project where I need to generate and send PayPal invoices. I wrote a function using PayPal's NodeJS SDK to create invoices, but for some reason, the drafted invoices don't show up in the sandbox dashboard. Currently, ...

Tips for evaluating an array of objects in JavaScript

Welcome to the world of coding! Here's a scenario with an array: [ { "question1": "Apple", "question2": 5, "question3": "Item 1" }, { "question1": ...

What is the best method for making certain rows uneditable in jqgrid?

Can rows be set as uneditable in jqgrid after the first edit is done? I attempted to add a class called not-editable-row but it did not work. This is how I currently make all rows editable: onSelectRow: function(id){ if(id && id!==lastsel){ g ...

Display or conceal information in a distinct container in AngularJS by selecting any cell in a table

In the following demonstration, I am displaying multiple values in a single cell of a table. If a particular row's cell has only one value, there is no action needed. However, if it contains more than one value, we can hide and show these values withi ...

Remove the JSON object by comparing IDs between two JSON objects in JavaScript or Node.js, deleting it if the ID is not found

let data = fetchData(); let anotherData = getAnotherData(); let result = data.reduce((accumulator, current) => { if (!accumulator[current.system.name]) { accumulator[current.system.name] = {}; } let detailsObject = {}; Object.keys(current. ...

Encountered an error while attempting to access property 'someProperty' of an undefined value in a React application

Currently, I am developing an application that involves passing variable values within a Navlink using state from one component to another. Once the values are received, they need to be loaded into input fields and then upon clicking the submit button in t ...

Pop-up with interactive content

I am trying to create a single popup that appears when different list elements are clicked, with each list element providing information for the popup. I attempted to implement this functionality but I am having trouble dynamically fetching the text from t ...

Tips for binding dropdownlist selected value using jquery in asp.net

I am currently developing an asp.net application where I need to incorporate Products. Below is the layout I have designed: <script type="text/javascript" language="javascript> function BindSubCategory() { var SubCategory = document.g ...

Looking for assistance to set up and configure Scatter (IOC) services?

I've been going over the example outlined on Services with a fine-tooth comb, but I just can't seem to get my implementation to function properly. It's baffling me beyond belief as to where exactly I might be making a mistake. My expectatio ...

Unable to transfer array elements to a function within PhantomJS

I am facing a challenge in extracting the source code from multiple webpages simultaneously. The links are stored in an array from a source text file. While I am able to successfully loop through the array and display the links, I encounter an issue when p ...

Refresh object attributes with newly retrieved data from MongoDB

I've been attempting to update object properties with new data retrieved from MongoDB. However, the following code isn't working as expected and I can't figure out why. Can anyone provide some assistance? var UserDB = require('../mode ...

Retrieve an array of objects using URLSearchParams

I am in need of extracting the array of objects named filter from a URL string: http://localhost:3006/menus?page=1&filter[0][id]=MenuID&filter[0][value]=2&filter[1][id]=ParentMenuName&filter[1][value]=u. This is my current approach: con ...

Challenges with importing and using jspdf and autotable-jspdf in Angular 8

Issue with Generating PDF Using Angular 8, JSPDF, and JSPDF-AutoTable I am facing a challenge with exporting/generating a PDF based on an HTML grid. I need to make some DOM changes with CSS, remove toggle buttons, alter the header, etc. However, all the s ...

The error message "NullInjectorError: No provider for HTTP!" is generated by the ionic-native/http module

Currently working with ionic 3.2 and angular. To install the HTTP module (https://ionicframework.com/docs/native/http/), I used the following commands: ionic cordova plugin add cordova-plugin-advanced-http npm install --save @ionic-native/http In my scri ...

What is the best way to access the list value within a component?

Let's say I've imported a component called <pic-upload> into the template like this: <template> <pic-upload></pic-upload> </template> export default { data: () => ({ show: { content: '', ...

Issue with Orgchart JS: The requested resource does not have the 'Access-Control-Allow-Origin' header present

Currently, I am developing a program to create organization charts using orgchart.js and simple PHP. This project does not involve any frameworks, but unfortunately, I encountered the following error: CORS policy is blocking access to XMLHttpRequest at & ...

Importing multiple exports dynamically in Next.js

My current setup involves using a third-party package that I load dynamically in Next.js: const am5 = dynamic(() => import("@amcharts/amcharts5"), {ssr: false}) The imported amcharts5 consists of various exports and imports, such as: export { ...

Leveraging async() functions within eval() - discord.js

I recently attempted to utilize the eval command in my bot with the use of 'await'. However, since await is only valid in async functions, I created a new command called aeval. The issue I am facing is that the aeval command is returning ...