【发布时间】:2021-09-07 08:47:01
【问题描述】:
我有如下代码,它使用了很多嵌套的 then 子句。此代码用于测试我用 javascript 编写的代码并使用 cypress 做出反应。
{
export const waitForItems = (retries, nrItems) => {
cy.apiGetItems().then(items => {
if(items.length!== nrItems && retries > 0) {
cy.wait(1000);
return waitForItems(retries -1, nrItems);
}
expect(items.length).to.be.equal(nrItems);
});
};
const item = {
name: 'name1',
};
const itemFamily = 'ItemFamily1';
const subfamily = {
name: 'subfamily1',
}
describe('some test', () => {
before(() => {
cy.clickButtonByLabel('Click');
switchUser(USERNAME);
waitForItems(NUMBEROFRETRIES, NUMBEROFITEMS);
cy.apiGetItems({ name: item.name })
.then(createdItem => {
item.id = createdItem[0].id;
})
.then(() => {
cy.apiGetItemFamily({
name: itemFamilyName,
}).then(family => {
cy.apiGetSubFamily({
name: subfamily1.name,
item__family__id__in: family[0].id,
}).then(subfamily => {
subfamily1.id = subfamily[0].id; //error here says cannot read
// id of undefined
cy.apiPostSomething({
...something,
items: [item.id],
subfamily: [subfamily1.id],
}).then(createdSomething => {
something.id = createdSomething.id;
cy.apiGetItemVariable({
key: ItemVariableName,
subfamily__id__in: subfamily1.id,
}).then(variable => {
cy.apiPostVariableValue({
variable: variable[0].id,
value: controlValue,
}).then(() => {
cy.apiGetsubFamily({
name: subfamily1.name,
}).then(newControl => {
const versions =
newControl[0].versions;
const latestVersionControl = versions.find(
v => v.version === '3.9.0'
);
const id = latestVersionControl.id;
cy.apiPatchSomething({
id: Something.id,
controls: [id],
});
});
});
});
});
});
});
});
});
上面的代码工作正常。但有时我在 then(subfamily) 子句中收到错误“无法读取未定义的 id”。
我不确定为什么 subfamily[0] 在尝试这样分配时仍然不可用
.then(subfamily => {
subfamily1.id = subfamily[0].id;
}
谁能帮我解决这个问题。谢谢。
【问题讨论】:
-
cy.apiGetSubFamily的内部结构导致了问题,因为你得到了它的结果。请提供此代码。 -
另外,您能说明
subfamily1的来源吗?它是在测试之外初始化的对象吗?
标签: javascript reactjs cypress