9

我正在使用chai-as-promised + mocha来编写一些selenium-webdriver测试。由于 webdriver 广泛使用promises,我想如果我对这些类型的测试使用 chai-as-promised 会更好。

问题是,当测试失败时,mocha 没有正确捕获错误,它只是失败而没有输出任何东西。

示例代码:

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)

根据记录的行为,当期望失败时, chai-as-promised应该将错误传递给 mocha。正确的?

作为一种变体,

我也试过这些,但无济于事:

#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()
4

1 回答 1

7

我认为你有两个不同的问题:

首先,您需要在测试结束时返回一个承诺(例如Q.all([...]);,在您的第一个测试中应该是return Q.all([...]).

其次,我发现chai-as-promised除非与mocha-as-promised.

这是一个mocha-as-promised带有两个将导致测试失败的断言的示例。

/* 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)
    ]);
  });
});
于 2014-03-06T23:12:20.410 回答