量角器getText()未设置为变量

Jef*_*eff 1 angularjs protractor

我正在测试我的管理员编辑其他用户的能力.该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');
}
Run Code Online (Sandbox Code Playgroud)

我还没有完成这expect部分.现在,我无法将当前名称(Bob)存储在变量中.它打印出空白:

Using the selenium server at http://localhost:4444/wd/hub
[launcher] Running 1 instances of WebDriver
Started
..............here

....
Run Code Online (Sandbox Code Playgroud)

如果我在函数内部使用console.log,它会输出正确的名称,但看起来我的承诺直到以后才能实现?

        fname.getText().then(function (txt) {
            console.log(txt);
            originalName = txt;
        });
        console.log('here');
        console.log(originalName);
        fname.sendKeys('New Name');
}
Run Code Online (Sandbox Code Playgroud)

给我这个:

Using the selenium server at http://localhost:4444/wd/hub
[launcher] Running 1 instances of WebDriver
Started
..............here

Bob
....
Run Code Online (Sandbox Code Playgroud)

如何在承诺之外获得该值(通过变量)?我只是做错了吗?

Dav*_*oni 7

简而言之,是的,你做错了.其中的代码在其then()后面的代码之后执行,因为在后一代码运行后履行了promise.坦率地说,这是编写量角器测试的一个棘手的部分.

有一些可能的解决方案:

  • 将代码添加到then()块中.
  • 将您的代码放在后续then()块中.
  • "等待"浏览器完成工作

所以第一个是显而易见的,第二个看起来像:

fname.getText().then(function (txt) {
    console.log(txt);
    originalName = txt;
}).then(function () {
    console.log('here');
    console.log(originalName);
});
fname.sendKeys('New Name');
Run Code Online (Sandbox Code Playgroud)

第三个看起来像:

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');
Run Code Online (Sandbox Code Playgroud)

另外值得注意的是,这只是在您关心console.log()业务的情况下.您注意到fname.sendKeys()代码在块之外 - 量角器将负责等待上一次操作完成,无论在执行下一次操作之前.如果你在茉莉花中使用getText(),量角器也会照顾你的承诺expect().