【发布时间】:2020-05-30 11:11:50
【问题描述】:
我有一个要求,我想在 n 次循环中读取特定值 x(每次自动生成)。现在,我想存储这些自动生成的 x 值,以便以后可以使用它们并对其进行迭代以执行我的测试(量角器)。
我想做的方法是使用let list: string[] = []; 创建一个数组。现在,我在每次迭代中使用list.push[x]; 将值推送到我定义的列表中。在循环结束时,期望在我的list 数组中获得具有 n 个 x(string) 值的数组。为了验证,我在每次迭代中都做了console.log(list);,我可以看到这些值被推送到定义的list中。
稍后,在我的代码中,如果我尝试使用 let item = list[0]; 访问这些元素,我将获得 undefined 值。
我认为我需要将数组初始化为具有默认值的特定大小,然后在循环中稍后修改它们。但是,作为 TypeScript 的新手,我无法找到有关如何执行此操作的解决方案。请帮助,TIA!
这里是下面的sn-p:
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.
});
// });
});
});
【问题讨论】:
-
我猜这是因为您没有正确使用推送功能。在您的示例中,您使用的是
list.push[x],但是,您可能正在寻找iten.push(x)。后者将添加一个元素做数组。要么就是你的代码中有其他东西正在重置数组。如果您发布代码的相关部分可能会有所帮助。 -
添加了我正在尝试做的事情的 sn-p。谢谢!
标签: arrays typescript protractor integration-testing undefined