问题
I'm using chai-as-promised + mocha for writing some selenium-webdriver tests. Since webdriver extensively uses promises, I imagined it would be better if I used chai-as-promised for those type of tests.
The problem is that when the tests fail, the error is not being caught properly by mocha, and it just fails without outputting anything.
Sample code:
it 'tests log', (next) ->
log = @client.findElement(By.css("..."))
Q.all([
expect(log.getText()).to.eventually.equal("My Text")
expect(log.findElement(By.css(".image")).getAttribute('src'))
.to.eventually.equal("/test.png")
]).should.notify(next)
According to documented behaviour, chai-as-promised should pass the errors along to mocha when the expectation fails. Right?
As a variation,
I've also tried these, but to no avail:
#2
# same, no error on failure
it 'tests log', (next) ->
log = @client.findElement(By.css("..."))
Q.all([
expect(log.getText()).to.eventually.equal("My Text")
expect(log.findElement(By.css(".image")).getAttribute('src'))
.to.eventually.equal("/test.png")
]).should.notify(next)
#3
# same, no error shown on failure
it 'tests log', (next) ->
log = @client.findElement(By.css("..."))
expect(log.getText()).to.eventually.equal("My Text")
.then ->
expect(log.findElement(By.css(".image")).getAttribute('src'))
.to.eventually.equal("/test.png").should.notify(next)
#4
## DOES NOT EVEN PASS
it 'tests log', (next) ->
log = @client.findElement(By.css("..."))
Q.all([
expect(log.getText()).to.eventually.equal("My Text")
expect(log.findElement(By.css(".image")).getAttribute('src'))
.to.eventually.equal("/test.png")
])
.then ->
next()
.fail (err) ->
console.log(err)
.done()
回答1:
I think you're having two different issues:
First, you need to return a promise at the end of your tests (e.g. Q.all([...]);
in your first test should be return Q.all([...])
.
Second, I found that chai-as-promised
doesn't seem to work unless used with mocha-as-promised
.
Here's an example of mocha-as-promised
with two assertions that will cause the test to fail.
/* jshint node:true */
/* global describe:false */
/* global it:false */
'use strict';
var Q = require('q');
require('mocha-as-promised')();
var chai = require('chai');
var chaiAsPromised = require('chai-as-promised');
chai.use(chaiAsPromised);
var expect = chai.expect;
describe('the test suite', function() {
it('uses promises properly', function() {
var defer = Q.defer();
setTimeout(function() {
defer.resolve(2);
}, 1000);
return Q.all([
expect(0).equals(0),
// the next line will fail
expect(1).equals(0),
expect(defer.promise).to.eventually.equal(2),
// the next line will fail
expect(defer.promise).to.eventually.equal(0)
]);
});
});
来源:https://stackoverflow.com/questions/20931737/chai-as-promised-is-eating-assertion-errors