【发布时间】:2018-12-04 20:36:14
【问题描述】:
我在理解 await 何时/如何在 TestCafé 中使用和需要时遇到了一些问题。
为什么这个函数的第一行需要await?
async getGroupCount(groupName) {
const groupFilterLinkText = await this.groupFilterLink.withText(groupName).textContent;
const openInd = groupFilterLinkText.indexOf('(');
const closeInd = groupFilterLinkText.indexOf(')');
const count = parseInt(groupFilterLinkText.slice(openInd + 1, closeInd), 10);
return count;
}
我后来在文档中发现它说“注意这些方法和属性获取器是异步的,所以使用 await 来获取元素的属性。”但是,我正在使用我以一种非常同步的方式编写的函数,所以这让我完全感到惊讶。我已经确保页面处于我希望它处于的状态,并且我只想解析一个字符串,但是这个函数的第 2 行的测试错误没有async/await。
与此相关,这是一个调用该函数的示例测试用例:
test('Verify an account owner can create a single user', async (t) => {
const userName = 'Single User';
const userEmail = 'singleuser@wistia.com';
const origUserCount = await usersPage.getGroupCount('All Users');
await t
.click(usersPage.addUserButton);
await waitForReact();
await t
.typeText(usersPage.addUserModal.nameInput, userName)
.typeText(usersPage.addUserModal.emailInput, userEmail)
.expect(usersPage.addUserModal.saveButton.hasAttribute('disabled')).notOk()
.click(usersPage.addUserModal.saveButton)
.expect(usersPage.userCard.withText(userName).exists).ok({ timeout: 10000 });
const newUserCount = await usersPage.getGroupCount('All Users');
await t
.expect(newUserCount).eql(origUserCount + 1);
});
最初,我测试的最后几行是这样的:
await t
...
.click(usersPage.addUserModal.saveButton)
.expect(usersPage.userCard.withText(userName).exists).ok({ timeout: 10000 })
.expect(await usersPage.getGroupCount('All Users')).eql(origUserCount + 1);
也就是说,它包含在整个测试的一个功能链中。这失败了,因为 await usersPage.getGroupCount('All Users') 的值仍在返回原始值而不是更新。我不明白为什么我需要将它分离到它自己对函数的调用中。为什么getGroupCount 似乎在测试开始时被评估,而不是在测试到达那行代码时?它的异步行为似乎不像我预期的那样。
【问题讨论】:
标签: javascript asynchronous testing e2e-testing testcafe