我声明使用testCafe一周,并且我需要使用不同的登录名/个人资料来测试一页。
当我仅一次登录(没有for循环)运行测试时,它可以工作。但是当我尝试使用for循环更改登录名时,它说没有用户文本:
import 'testcafe';
import { Selector, ClientFunction } from 'testcafe';
var user = ['admin','sales.test'];
var pass = ['admin','Test@123'];
var role = ['Admin','Sales'];
var x;
for ( x=0; x < user.length; x++)
{
fixture('Compass - Main page - Profile: ' + role[x])
.page('http://localhost:3000/')
.beforeEach(async t => {
//login
await t.typeText(Selector('input').withAttribute('name','username'), user[x], {
paste: true,
replace: true,
});
await t.typeText(Selector('input').withAttribute('name','password'), pass[x], {
paste: true,
replace: true,
});
await t.click(Selector('button').withAttribute('tabindex','0'));
})
.afterEach(async t => {
//logout
await t.click(Selector('#logoutBtn'));
});
test('Check if the Main page is loading (button debug).', async t => {
await t.expect(
Selector('#toggleNotifier').exists,
).ok();
});
test('Check if the Organization page is loading...', async t => {
await t.click(Selector('a').withAttribute('href','#organizations'));
await t.expect(
Selector('a').withAttribute('href','/#/organizations/new').exists,
).ok();
});
}
我使用的命令:testcafe edge .\roles_spec.ts
我得到的结果:
PS C:\ThinkOn\Compass_Test\Test1> testcafe edge .\roles_spec.ts
Using locally installed version of TestCafe.
Running tests in:
- Microsoft Edge 17.17133 / Windows 10
Compass - Main page - Profile: Admin
× Check if the Main page is loading (button debug).
1) - Error in fixture.beforeEach hook -
The "text" argument is expected to be a non-empty string, but it was undefined.
Browser: Microsoft Edge 17.17133 / Windows 10
12 | fixture('Compass - Main page - Profile: ' + role[x])
13 | .page('http://localhost:3000/')
14 | .beforeEach(async t => {
15 |
16 | //login
> 17 | await t.typeText(Selector('input').withAttribute('name','username'), user[x], {
18 | paste: true,
19 | replace: true,
20 | });
21 | await t.typeText(Selector('input').withAttribute('name','password'), pass[x], {
22 | paste: true,
at <anonymous> (C:\ThinkOn\Compass_Test\Test1\roles_spec.ts:17:21)
at <anonymous> (C:\ThinkOn\Compass_Test\Test1\roles_spec.ts:8:71)
at __awaiter (C:\ThinkOn\Compass_Test\Test1\roles_spec.ts:4:12)
at fixture.page.beforeEach (C:\ThinkOn\Compass_Test\Test1\roles_spec.ts:14:31)
at <anonymous> (C:\ThinkOn\Compass_Test\Test1\node_modules\testcafe\src\api\wrap-test-function.js:17:28)
at TestRun._executeTestFn (C:\ThinkOn\Compass_Test\Test1\node_modules\testcafe\src\test-run\index.js:295:19)
at TestRun._runBeforeHook (C:\ThinkOn\Compass_Test\Test1\node_modules\testcafe\src\test-run\index.js:316:31)
at TestRun.start (C:\ThinkOn\Compass_Test\Test1\node_modules\testcafe\src\test-run\index.js:344:24)
这是变量范围的问题。在您的代码中,x变量是使用var语句声明的,并且具有全局作用域。由于每个钩子之前的代码都是异步执行的,因此它使用x在for循环完成后将具有的值,并且user [x]表达式将是未定义的。
为了避免这种情况,请在for块中使用let语句:
for(let x = 0; x++; x< users.length)
更多信息,请参阅https://www.typescriptlang.org/docs/handbook/variable-declarations.html#block-scoping