Understanding the concept of dynamic arrays in Typescript?

In my current project, I have a specific requirement that involves reading an auto-generated value "x" in a loop for a certain number of times (let's say "n"). I need to store these auto-generated values of "x" so that I can later use them for performing tests, particularly with Protractor.

To achieve this, I decided to create an Array in TypeScript by initializing it as let list: string[] = [];. During each iteration, I am pushing the values of "x" to this list using list.push[x];. By the end of the loop, I expect to have an Array with "n" values of "x" stored in my list. To validate this, I added console.log(list); in each iteration and confirmed that the values are being successfully pushed to the list.

However, when I try to access these elements using let item = list[0];, I am encountering an issue where the value returned is undefined.

I believe that I may need to initialize the Array with a specific size and default values initially, and then modify them during the loop. As a newcomer to TypeScript, I am struggling to find a solution for this problem. Any assistance would be greatly appreciated. Thank you in advance!

Below is a snippet of the code:

    const tests = [
{type: 'admin', id='', uname='foo', pass='bar'},
{type: 'super', id='', uname='foo1', pass='bar'},
{type: 'normal', id='customId', uname='foo', pass='bar'}
];

let list: string[] = [];
// let list = [         //this is the final list that i got from the console.log(list);
// 'QR417msytVrq',
// 'V0fxayA3FOBD',
// 'QnaiegiVoYhs'];

describe(`Open Page `, () => {
  //Code to get to the page

  beforeAll(async () => {
    //initialize page objects

  });

  describe(`Login User `, async () => {
    tests.forEach(test => {
      it(` should login user with `+test.type, async () => {

        //....
        //....


        // On Success
        const myId = userPage.getUID().getText();

        list.push(myId);
        console.log(list);
        console.log(list.length);
      });
    });
  });


  describe(`Delete User`, async () => {

    // describe(`Confirmation `, async () => {
    console.log(list);
    // list.forEach(item => {       //this code doesn't get executed and wasn't giving any error, so, commented out and tried to access the first element which is undefined.
      let item = list[0];
      console.log(item);            //getting undefined value here. 
      it(` should select and Delete the User having id as ` + item, async () => {
        //code to remove the user having id as item.
      });
    // });
  });
});

Answer №1

Effective Methods for Testing User Deletion:

It's generally advised against making tests reliant on other tests, as it can lead to poor testing practices. However, there are a few options you can consider:

A: Sequential User Deletion Testing

describe(`Delete User`, async () => {
    describe(`Confirm Deletion`, () => {
        it(`Log out previously logged-in users`, async () => {
            list.forEach((item) => {
                console.log(item);
            });
        });
    });
});

By using the populated 'list' array from the previous test, you can ensure that the values required for testing deletion are available.

B: Combined Login and Deletion Testing

describe(`Login and Delete User`, async () => {
    tests.forEach(test => {
        it(`Should login and delete user with ` + test.type, async () => {
            const myId = userPage.getUID().getText();
            // Perform user deletion here
        });
    });
});

You may choose to consolidate the user flow into a comprehensive integration test to eliminate the need for the 'list' array.

C: Mock Data Usage (Not Suitable for Random Data)

describe(`Delete User`, async () => {
    const list = ["QR417msytVrq", "V0fxayA3FOBD", "QnaiegiVoYhs"];
    describe(`Confirm Deletion `, () => {
        list.forEach((item) => {
            it(
                `Should select and delete the user with ID ` + item,
                async () => {}
            );
        });
    });
});

Manually adding known deletion values can be effective, unless the data is randomly generated.

Additional Notes:

Issue with Execution Order Testing

The test structure may be causing an execution order problem, specifically when trying to access 'list[0]' before 'Login User' specs run:

A simple solution could be renaming the 'Delete User' spec and organizing the code within the specs accordingly.

Avoiding Promise Returns from Describe Blocks

Ensure that 'describe' blocks do not return promises by removing 'async' from function declarations. The specs should remain as they are.

Correct Object Syntax Usage

The initial 'tests' object should use JS/TS object syntax for better clarity:

Sources:

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

Using Angular's ElementRef to set focus on an ion-textarea: "The 'setFocus' property is not found on the 'ElementRef' type."

After developing a textarea component that automatically focuses itself when created using the ngAfterViewInit() method, everything seemed to be working perfectly as expected. ngAfterViewInit() { if(this.text.length===0){ this.theinput.setFocus(); ...

Developing a continuous running test loop

Currently, I have a code that runs fine, but I am looking to modify it to run in a loop that counts the number of elements with the class="socal" and tests each link. module.exports = { 'Unitel Fitness - click' : function (browser) { bro ...

Ran out of memory while trying to allocate bytes for sending a Bitmap as a String to a webservice via soap communication

I currently have a bitmap that I want to convert to a string and then upload to a web service in order to retrieve the string. To convert the bitmap to a string, I am using the following code: ByteArrayOutputStream stream = new ByteArrayOutputStream(); b ...

How can a property be made mandatory in Typescript when another property is set as optional?

Currently, I am unsure about what to search for in order to fulfill the following requirement. Specifically, I am utilizing the given type for react props: interface ComponentProps { message : string, minValue? : number, minValueValidationMessage? ...

How can I adjust the padding and width attributes of the mat-menu in Angular 5

Today, I am struggling with a piece of code. Whenever I click on the Details button, it is supposed to open a mat-menu. However, for some reason, I cannot seem to adjust the padding or width of the menu: <div id="box-upload" [hidden]="hiddenBoxUpload" ...

When attempting to import a component from an external library in React/Next, you may run into an error that states: "Element type is invalid: Expected a string or

I am currently working on developing a React components library that can be seamlessly integrated into a NextJs project. The library includes a versatile "CmsBlock" component which takes a type and data as inputs to generate either a Paragraph or ZigZag co ...

Measuring vocabulary through synchronized Java arrays

Struggling with creating a code to calculate the frequency of words in an array. Is it necessary to use nested loops to keep track of both the word array and integer array? Despite spending hours on this, I haven't been able to make any progress. Any ...

TypeScript implements strong typing for object strings

Is it possible to create a custom type in TypeScript that represents a stringified object with a specific structure? Instead of just defining type SomeType = string, I would like to define a type that looks something like this: type SomeType = Stringified ...

Guide on incorporating properties into a component with TypeScript and React

In my Parent Component, I am passing RouteComponentProps as shown below, function Parent({ history }: RouteComponentProps) { //some logic } Now, I want to introduce a new prop called OpenByDefault in the Parent component like this, interface Props { ...

The message "Expected a string literal for Angular 7 environment variables" is

I'm currently working on setting up different paths for staging and production environments in my Angular project, following the documentation provided here. I have a relative path that works perfectly fine when hardcoded like this: import json_data f ...

Why do I keep being told that the property doesn't exist?

I have the following code in one file: function test<T extends {}>(arg:T):any { return arg.name } In another file, I have this code: interface IItem { name: string } console.log(test<IItem>({name:'3'})) When I try to access ...

Utilizing Directives to Embed Attributes

My current challenge involves changing the fill color of attributes in an in-line SVG using Angular and TypeScript. The goal is to have the SVG elements with a "TA" attribute change their fill color based on a user-selected color from a dropdown menu. Howe ...

Show the user's chosen name in place of their actual identity during a chat

I'm facing an issue where I want to show the user's friendly name in a conversation, but it looks like the Message resource only returns the identity string as the message author. I attempted to retrieve the conversation participants, generate a ...

How can one utilize JSON.parse directly within an HTML file in a Typescript/Angular environment, or alternatively, how to access JSON fields

Unable to find the answer I was looking for, I have decided to pose this question. In order to prevent duplicates in a map, I had to stringify the map key. However, I now need to extract and style the key's fields in an HTML file. Is there a solution ...

Assign a value to a variable using a function in Typescript

Is there a way in typescript to explicitly indicate that a function is responsible for assigning value to a variable? UPDATED CODE Here, the code has been simplified. While getText() ensures that it will never be undefined, this may not hold true in subs ...

What is the best way to change a String into an Array within MongoDB?

I need help with converting the type of an object that has been changed. Is there a way to transform this: { "_id" : NumberLong(257), "address" : "street Street, house 50, appartment 508, floor 5" } into this: { "_id" : NumberLong(257), "userAddres ...

Angular 10 encountering an issue with subject instantiation

I am encountering an issue with my Angular application. Everything runs smoothly with `ng serve`, and the application builds correctly using `ng build --prod`. However, when I attempt to run the generated sources in the browser, an error occurs: TypeError: ...

Correctly inputting the 'in' statement - Avoid using a primitive value on the right side of an 'in' statement

I am currently facing an issue with my React code where I am getting the error message: The right-hand side of an 'in' expression must not be a primitive.. I am unsure about how to resolve this problem effectively: // The goal is to allow nu ...

Error message "Cannot find children property on type IntrinsicAttributes & RefAttributes<unknown>" occurring in a React component due to a Typescript issue

Issue: The specified type '{ children: string; severity: string; sx: { width: string; }; }' is not compatible with the type 'IntrinsicAttributes & RefAttributes'. The property 'children' is missing in the type 'Intri ...

Implementing tailwindcss styles in a typescript interface with reactjs

In my code, I have a file named types.ts that defines an interface called CustomCardProps. I pass this interface to the CustomCard component within the home.tsx file. Additionally, I have a folder named constant with an index.ts file where I store values o ...