我正在测试管理员编辑其他用户的能力。我正在检查user.firstname
模型。我希望能够将第一个名称设置回测试后的最初名称。
it("should be able to edit a different profile.", function () {
browser.get('#/user/2');
var fname = element(by.model('user.firstName'));
var originalName = '';
fname.getText().then(function (txt) {
originalName = txt;
});
console.log('here');
console.log(originalName);
fname.sendKeys('New Name');
}
我还没有进入expect
部分。现在,我无法将当前名称(Bob)存储在变量中。它打印出空白:
Using the selenium server at http://localhost:4444/wd/hub
[launcher] Running 1 instances of WebDriver
Started
..............here
....
如果我在函数内部使用console.log,它会打印出正确的名称,但看起来我的承诺直到以后才能实现?
fname.getText().then(function (txt) {
console.log(txt);
originalName = txt;
});
console.log('here');
console.log(originalName);
fname.sendKeys('New Name');
}
给了我这个:
Using the selenium server at http://localhost:4444/wd/hub
[launcher] Running 1 instances of WebDriver
Started
..............here
Bob
....
如何在承诺之外获得该值(通过变量)?我只是做错了吗?
答案 0 :(得分:7)
简而言之,是的,你做错了。 then()
中的代码在其后面的代码之后执行,因为在后一代码运行后履行了承诺。坦率地说,这是编写量角器测试的一个棘手的部分。
有一些可能的解决方案:
then()
块。then()
块中。所以第一个显而易见,第二个看起来像:
fname.getText().then(function (txt) {
console.log(txt);
originalName = txt;
}).then(function () {
console.log('here');
console.log(originalName);
});
fname.sendKeys('New Name');
第三个看起来像:
fname.getText().then(function (txt) {
console.log(txt);
originalName = txt;
});
// ... do stuff ...
browser.wait(function() {
return originalName !== undefined;
}).then(function() {
console.log('here');
console.log(originalName);
});
fname.sendKeys('New Name');
此处还值得注意的是,只有在您关注console.log()
业务时才会这样做。您注意到fname.sendKeys()
代码在块之外 - 在执行下一个操作之前,量角器将负责等待上一次操作完成。如果你在茉莉花expect()
中使用getText(),量角器也会照顾你的承诺。