【问题标题】:Why wont mocha wait for chai as promised to finish?为什么 mocha 不按承诺等待 chai 完成?
【发布时间】:2018-07-27 20:10:50
【问题描述】:

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

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.

【问题讨论】:

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


    【解决方案1】:

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

    1. 使用测试函数的第一个参数:done
    2. 返回承诺

    您可以在此处阅读有关Mocha Asynchronous Tests 的更多信息。

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

      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 这样做。

    【讨论】:

      猜你喜欢
      • 2019-04-29
      • 2017-06-17
      • 2021-10-03
      • 2018-03-05
      • 2016-10-16
      • 2020-11-03
      • 2021-10-14
      相关资源
      最近更新 更多