简体   繁体   English

在 Typescript 中定义动态数组?

[英]Defining dynamic Array in Typescript?

I have a requirement where i want to read a particular value x(that is auto-generated everytime) in a loop of say n times.我有一个要求,我想在 n 次循环中读取特定值 x(每次自动生成)。 Now, i want to store these autogenerated values of x, so, that i can later use them and iterate over it to perform my tests(protractor).现在,我想存储这些自动生成的 x 值,以便以后可以使用它们并对其进行迭代以执行我的测试(量角器)。

The way, i am trying to do is by creating an Array, using let list: string[] = [];我想做的方法是创建一个数组,使用let list: string[] = []; . . Now, i am pushing the values to my defined list using, list.push[x];现在,我正在使用list.push[x];将值推送到我定义的列表中。 in each iteration.在每次迭代中。 By the end of loop expecting to get the resulting Array having n values of x(string) in my list array.在循环结束时,期望在我的list数组中获得具有 n 个 x(string) 值的数组。 In order to validate, i did console.log(list);为了验证,我做了console.log(list); in each iteration and i can see that these values are being pushed in the defined list .在每次迭代中,我可以看到这些值被推送到定义的list

Later, in my code if i am trying to access these elements using let item = list[0];稍后,在我的代码中,如果我尝试使用let item = list[0];访问这些元素i am getting the undefined value.我得到了undefined的值。

I think i need to initialize the Array to some particular size having default values initially and then modify them later in the loop.我想我需要将数组初始化为最初具有默认值的特定大小,然后在循环中稍后修改它们。 But, being new to TypeScript i am not able to find a solution on how to do it.但是,作为 TypeScript 的新手,我无法找到解决方案。 Please help, TIA!!请帮助,TIA!

Here, is the snippet below:这里,是下面的片段:

    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 gets 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.
      });
    // });
  });
});

Options to test deleting a user:测试删除用户的选项:

Ultimately, it's bad practice to make tests dependent on other tests .最终, 使测试依赖于其他测试是不好的做法

That said, two or possibly three options which should work:也就是说,两个或可能三个应该起作用的选项:

A: Iterate through list of users within one test A:在一个测试中遍历用户列表

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

Since the list array is populated by the previous test, inserting the code dependent on it inside of the next test would ensure that it has values to work with.由于list数组由上一个测试填充,因此将依赖于它的代码插入到下一个测试中将确保它具有可使用的值。

B: Login and delete user in one test B:一次测试登录和删除用户

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

You may be able to remove the list array entirely by putting the entirety of the user flow into one large integration test.您可以通过将整个用户流放入一个大型集成测试中来完全删除list数组。

C: Use mock data (may not be applicable if data is random) C:使用模拟数据(如果数据是随机的,可能不适用)

describe(`Delete User`, async () => {
    const list = ["QR417msytVrq", "V0fxayA3FOBD", "QnaiegiVoYhs"];
    describe(`Confirmation `, () => {
        list.forEach((item) => {
            it(
                ` should select and Delete the User having id as ` + item,
                async () => {}
            );
        });
    });
});

If you know what the values to delete are going to be ahead of time, you can add them in manually.如果您提前知道要删除的值是什么,则可以手动添加它们。 If the values are randomly generated, this won't work.如果这些值是随机生成的,这将不起作用。

Other problems:其他问题:

Testing order of execution测试执行顺序

The dynamic array syntax you're using looks right however you appear to have an order of execution problem in your tests.您使用的动态数组语法看起来不错,但是您的测试中似乎存在执行顺序问题。

The code in the describe functions that is outside of the specs (the it blocks) is executed before any of the code inside of the specs is.规范之外的describe函数中的代码( it块)在规范内的任何代码之前执行。 The testing framework will traverse the tree of describe blocks, executing any code it finds but only taking note of the it specs.测试框架将遍历describe块树,执行它找到的任何代码,但只记录it的规范。 When it's finished this, it then executes the it specs it found in sequential order.完成此操作后,它会按顺序执行找到的it规范。

When you attempt to save the value of list[0] , the 'Login User' specs have yet to be executed.当您尝试保存list[0]的值时, 'Login User'规范尚未执行。 More specifically:进一步来说:

describe(`Login User `, async () => {
    tests.forEach(test => {
        it(` should login user with ` + test.type, async () => {
            // This code is executed AFTER the code in the 'Delete User' 
            // block but BEFORE the 'Delete User' spec
            const myId = userPage.getUID().getText();
            list.push(myId);
        });
    });
});


describe(`Delete User`, async () => {
    // This code is executed before any specs are run
    let item = list[0];
    // List is [] when item is initialized
    // The following spec will therefore not work as item is undefined
    it(` should select and Delete the User having id as ` + item, async () => {
    });
});

A possible solution to this would be to change the string of the 'Delete User' spec to something like ' should select and Delete first User' as well as move all the code outside of the spec to inside.一个可能的解决方案是将'Delete User'规范的字符串更改为' should select and Delete first User' ,并将规范之外的所有代码移到内部。

Describe blocks should not return promises描述块不应该返回承诺

Your code sample has describe blocks (specifically 'Login User' , 'Delete User' , and 'Confirmation' ) which return Promises.您的代码示例describe了返回 Promises 的块(特别是'Login User''Delete User''Confirmation' )。 You should remove the async in front of the function declarations.您应该删除 function 声明前面的async The specs can and should remain the same.规格可以而且应该保持不变。 For example:例如:

describe(`Login User `, () => {

Object syntax Object 语法

The tests object at the start of your sample isn't using JS/TS object syntax.示例开头的测试 object 未使用 JS/TS object 语法。 Each key should be followed by a colon before the value instead of an equals sign.每个键的值前应该跟一个冒号,而不是等号。 You likely meant to write:你可能打算写:

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

Sources:资料来源:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM