问题描述
我已经用Google搜索过,可以找到如何遍历我的数据文件。显然,您对每个数据记录都进行了测试。
我想登录一次测试,然后循环浏览数据文件的每个“记录”或项目。数据是我们应用中的一系列搜索。因此,测试将登录并断言已登录,然后运行这些搜索...
test('searches',async t => {
await t
// Log in...
.typeText('input[id="login-name"]','aguy')
.typeText('input[id="login-password"]','bbb')
.click('button[id="signin-button"')
.expect(Selector('span[id="logged-in-user"]').innerText).contains('Hal')
// At this point the app is ready to run through the searches doing this...
// forEach item in my data...
.typeText('input[id="simplecriteria"]',data.criteria)
.click('button[class="search-button"]')
.expect(Selector('div[class="mat-paginator-range-label"]').innerText).contains(data.srchResult)
});
解决方法
TestCafe有test hooks,尽管它们在您的情况下不太有用,但我还是建议您使用它们,因为TestCafe会删除测试之间的cookie,因此,如果您登录一次,然后像这样编写测试,则:
const testData = require('../Resources/testData.json');
let executed = false;
fixture `Searches`
.page(baseUrl)
.beforeEach(async t => {
if (!executed) {
// run this only once before all tests
executed = true;
// log in
await t
.typeText('input[id="login-name"]','aguy')
.typeText('input[id="login-password"]','bbb')
.click('button[id="signin-button"')
.expect(Selector('span[id="logged-in-user"]').innerText).contains('Hal');
}
});
testData.forEach((data) => {
test('Searches',async t => {
await t
.typeText('input[id="simplecriteria"]',data.criteria)
.click('button[class="search-button"]')
.expect(Selector('div[class="mat-paginator-range-label"]').innerText).contains(data.srchResult);
});
});
那么您极有可能在首次测试后退出。
但是,我仍然使用beforeEach
钩子,但是将循环放入测试中:
const testData = require('../Resources/testData.json');
fixture `Searches`
.page(baseUrl)
.beforeEach(async t => {
await t
// Log in...
.typeText('input[id="login-name"]','aguy')
.typeText('input[id="login-password"]','bbb')
.click('button[id="signin-button"')
.expect(Selector('span[id="logged-in-user"]').innerText).contains('Hal');
});
test('Searches',async t => {
testData.forEach((data) => {
await t
.typeText('input[id="simplecriteria"]',data.criteria)
.click('button[class="search-button"]')
.expect(Selector('div[class="mat-paginator-range-label"]').innerText).contains(data.srchResult);
});
});
有明显的缺点:
- 许多不同的搜索被添加为一项测试,因此,如果一项测试失败,则整个“搜索”测试用例将被标记为失败
另一种解决方案可能是找出登录的含义。如果要添加一些cookie,则可以登录一次,然后仅在测试之前设置cookie。但是,在许多现代系统中,此类“登录cookie”将带有httpOnly
标志,因此您无法真正在JavaScript中进行设置。