我正在尝试使用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.
答案 0 :(得分:1)
有两种方法可以使mocha
测试异步。
done
。您可以在此处详细了解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
。