为什么摩卡不会像承诺的那样等待柴?

时间:2018-02-16 21:07:58

标签: node.js selenium-webdriver promise mocha chai

我正在尝试使用selenium,mocha和chai-as-promise来测试Web应用程序。我似乎无法让摩卡等待chai-as-promise的断言得到解决。我的测试代码如下所示:

var selenium = require('selenium-webdriver')
var By = selenium.By
var chai = require('chai')
var cap = require('chai-as-promised')
chai.use(cap)
expect = chai.expect

describe('Test Group', function() {
  var driver
  before(function() {
    driver = new selenium.Builder()
      .withCapabilities(selenium.Capabilities.chrome())
      .build()
    driver.getWindowHandle()
  })

  after(function() {
    driver.sleep(500).then(function() {
      driver.quit()
    })
  })

  describe('Authentication', function() {
    describe('#login redirect', function() {
      it('should redirect to /users/login when not logged in', function() {
        driver.get('http://127.0.0.1:3000/')
        driver.sleep(500).then(function() {
          return expect(driver.getCurrentUrl()).to.eventually.contain('WONT CONTAIN THIS')
        })
      })
    })
  })
})

尽管断言无法进行,但测试总是通过。测试还会返回这些错误:

  Test Group
    Authentication
      #login redirect
        ✓ should redirect to /users/login when not logged in


  1 passing (34ms)

(node:24883) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): AssertionError: expected 'http://127.0.0.1:3000/users/login' to include 'WONT CONTAIN THIS'
(node:24883) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

1 个答案:

答案 0 :(得分:1)

有两种方法可以使mocha测试异步。

  1. 使用测试功能的第一个参数:done
  2. 回复承诺
  3. 您可以在此处详细了解Mocha Asynchronous Tests

    在您的情况下,您已经在使用承诺,因此最简单的解决方案是返回您的承诺。像这样:

      it('should redirect to /users/login when not logged in', function() {
        driver.get('http://127.0.0.1:3000/')
        return driver.sleep(500).then(function() { // <------- return this promise
          return expect(driver.getCurrentUrl()).to.eventually.contain('WONT CONTAIN THIS')
        })
      })
    

    这也与您的after功能相关。现在编写它的方式,after函数将在内部promise被解析之前完成。你可以这样做它是异步的:

      after(function() {
        return driver.sleep(500).then(function() {
          driver.quit()
        })
      })
    

    请注意,如果driver.quit()返回承诺,您可能也应该return