Nightwatch:比.pause(1000)更好的方法来避免脆弱的测试

Nightwatch: Better way than `.pause(1000)` to avoid brittle tests?

本文关键字:方法 测试 脆弱 更好 pause 1000 Nightwatch      更新时间:2023-09-26

.pause(1000)真的是等待表单提交的最佳实践吗?我正在寻找一种方法来可靠地提交表单,而不必知道有关页面的细节出现作为表单提交的结果。

主页上的示例使用.pause(1000)来等待表单提交,具有讽刺意味的是,它不再工作了,但这个版本修改了css选择器版本:

module.exports = {
  'Demo test Google' : function (client) {
    client
      .url('http://www.google.com')
      .waitForElementVisible('body', 1000)
      .assert.title('Google')
      .assert.visible('input[type=text]')
      .setValue('input[type=text]', 'rembrandt van rijn')
      .waitForElementVisible('button[name=btnG]', 1000)
      .click('button[name=btnG]')
      .pause(1000)
      // This selector is different from the home page's - this one
      // works...
      .assert.containsText('ol#rso div.g:first-of-type',
        'Rembrandt - Wikipedia')
  }
};

.pause(1000)的问题,以确保表单得到提交是如何确定超时。要么是如果超时时间太长,将使我们的测试变慢;如果超时时间太短,将使测试变得脆弱。缓慢的硬件,服务器上的其他进程,月亮对齐,你的名字可以影响什么是"好的"超时值。

有没有更好的方式说:"等待表格提交之前……继续"?

我们已经试验了.waitForElementVisible('body', VERY_LONG_TIMEOUT)代替,它似乎工作,不需要比必要更长的时间,但我猜这也不可靠。它只工作,因为"当前"页面已经消失(这次),所以我们正在等待"新"页面的主体出现。明天会发生一些奇怪的事情,它会比平常快,.waitForElementVisible('body')会立即返回,因为旧的页面还在那里。==也易碎。对吗?

如果是,是否有比.pause(1000).waitForElementVisible('body')吗?尤其是如果我们不太了解页面在提交后返回,所以我们不能.waitForElementVisible('.element-only-on-new-page') ?

我问的原因是我们的测试实际上看起来更像:

module.exports = {
  'Test1 - submit form' : function (client) {
    client
      .url('http://some/url')
      .waitForElementVisible('body', 1000)
      .assert.title('MyTitle')
      .setValue('input[name="widget"]', 'value')
      // Click to submit the form to change some internal state
      .click('button[name="postForm"]')
      // Form got submitted fine in chromium 42 every single time. chromium
      // 45 needs additionally:
      //
      // .pause(1000)
      // or
      // .waitForElementVisible('body', 1000)
  }
  'Test2 - continue using new value' : function (client) {
    client
      .url('http://some/other/url')
      .waitForElementVisible('body', 1000)
      .assert.title('MyOtherTitle')
      .setValue('input[name="widget2"]', 'value2')
      .waitForElementVisible('.bla-bla', 1000)
  }
};

这是因为'http://some/url'的表单不再被提交铬45:-(我们想找到一个好的解决方案,而不仅仅是一个似乎在今天的条件下工作…

您是否尝试将waitForElementNotVisiblewaitForElementVisible链接为body html?这应该只等待每一步的适当时间。我会做一些测试,以确保它不脆。我们用它来监控单页应用程序中的"模拟页面转换"。

module.exports = {
  'Test1 - submit form' : function (client) {
    client
      .url('http://some/url')
      .waitForElementVisible('body', 1000)
      .assert.title('MyTitle')
      .setValue('input[name="widget"]', 'value')
      // Click to submit the form to change some internal state
      .click('button[name="postForm"]')
      .waitForElementNotVisible('body', 5000)
      .waitForElementVisible('body', 10000)
  }
};