使用Chai作为承诺解决量角器和黄瓜的承诺

And*_*hum 6 javascript angularjs chai protractor cucumberjs

最近一位同事和我对使用Protractor和Chai作为承诺实施Cucumber步骤定义的"正确"方法存在一些分歧.我们的论点来自于对Cucumber背景下的承诺解决方案的准确性的完全缺乏了解.

我们正在测试AngularJS应用程序,因此解决promise和异步行为是必要的恶魔.我们遇到的最大问题是强制同步测试行为并让Cucumber等待步骤定义之间的承诺.在某些情况下,我们观察到的情况是,在Webdriver甚至执行它们之前,Cucumber似乎直接通过步骤定义.我们对这个问题的解决方案各不

考虑假设情景:

Scenario: When a user logs in, they should see search form
  Given a user exists in the system
  When the user logs into the application
  Then the search form should be displayed
Run Code Online (Sandbox Code Playgroud)

大多数混淆起源于Then步骤.在此示例中,定义应声明页面上存在搜索表单的所有字段,这意味着多个isPresent()检查.

从我能够找到的文档和示例中,我觉得断言看起来应该是这样的:

this.Then(/the search form should be displayed/, function(next) {
    expect(element(by.model('searchTerms')).isPresent()).to.eventually.be.true;
    expect(element(by.model('optionsBox')).isPresent()).to.eventually.be.true;
    expect(element(by.button('Run Search')).isPresent()).to.eventually.be.true.and.notify(next);
});
Run Code Online (Sandbox Code Playgroud)

但是,我的同事认为,为了满足承诺解决方案,您需要使用then()链接您的期望,如下所示:

this.Then(/the search form should be displayed/, function(next) {
    element(by.model('searchTerms')).isPresent().then(function(result) {
        expect(result).to.be.true;

    }).then(function() {
        element(by.model('optionsBox')).isPresent().then(function(result) {
            expect(result).to.be.true;

        }).then(function() {
            element(by.button('Run Search')).isPresent().then(function(result) {
                expect(result).to.be.true;
                next;
            });
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

后者对我来说感觉真的不对,但我不知道前者是否正确.我最终理解的方式()是它与then()的工作方式类似,因为它在继续之前等待承诺解决.我希望前面的例子按顺序等待每个expect()调用,然后通过最终expect()中的notify()调用next()来发信号给黄瓜继续下一步.

为了增加更多的困惑,我观察到其他同事写下这样的期望:

expect(some_element).to.eventually.be.true.then(function() {
    expect(some_other_element).to.eventually.be.true.then(function() {
        expect(third_element).to.eventually.be.true.then(function() {
            next();
        });
    });
});
Run Code Online (Sandbox Code Playgroud)

所以我认为我提到的问题是:

  • 以上任何一种都有点对吗?
  • 最终()真正做了什么?它会像then()一样强制同步行为吗?
  • and.notify(下一个)真正做了什么?它与在then()中调用next()不同吗?
  • 是否有一个我们还没有找到的最佳实践指南,可以更清楚地说明这一点?

提前谢谢了.

小智 4

  • 你的感觉是正确的,你的同事错了(尽管这是一个合理的错误!)。Protractor 在运行第二个命令之前会自动等待一个 WebDriver 命令解析。因此,在您的第二个代码块中,直到和都完成后element(by.button('Run Search')).isPresent()才会解析。element(by.model('optionsBox')).isPresent()element(by.model('searchTerms')).isPresent()
  • eventually解决承诺。解释如下:https ://stackoverflow.com/a/30790425/1432449
  • 我不相信这与放入next()其中有什么不同then()
  • 我不认为有最佳实践指南。Cucumber 并不是 Protractor 团队的核心关注点,对其的支持主要由 github 上的社区提供。如果您或您认识的人想要编写最佳实践指南,我们(量角器团队)将欢迎 PR!