我正在使用testcafe来推动一个网站。我创建了一个页面模型,我可以单击我已经创建的按钮。
但是,我的页面使用React创建一个模态对话框,只有在单击按钮后才能看到该对话框。我可以使用document.querySelectorAll('.modal-footer > button')[1]
的浏览器控制台获取元素。
所以在我的页面模型中我使用了Selector('.modal-footer > button').nth(1);
,我也尝试使用here中的语法创建一个选择器。在这两种情况下,testcafe都无法找到该元素,我最终得到了TypeError: Cannot read property 'createElement' of null
错误。
这是我的代码:
// page model
import { Selector } from 'testcafe';
export class PageModel {
constructor () {
... // a bunch of buttons
this.modalButton = Selector('.modal-footer > button').nth(1);
}
}
和我的考验
// test script
import { PageModel } from 'page_model'
const pagemodel = new PageModel();
fixture ...
test('My Test', async t => {
await t.click(pagemodel.abutton);
await t.click(pagemodel.openDialog); // the modal dialog opens
await t.click(pagemodel.modalButton) // <-- Here's where I get the error
});
如果按钮可见(if (modalButton.exists)
),使用仅单击按钮的If语句似乎有效。但是,点击后该按钮消失后仍然出现错误。
有什么建议?
我能用try-catch块解决。我认为浏览器中存在一些导致测试失败的竞争条件。
const max_retries = 3
let count = 0;
while (count < max_retries) {
try {
await t
.click(pagemodel.modalButton);
break;
}
catch (e) {
console.error('An error occurred, trying again...');
count++;
if (count === retries) {
throw e;
}
}
}