Chai-As-Promised正在吃断言错误

时间:2014-01-05 08:51:27

标签: selenium testing mocha chai chai-as-promised

我正在使用 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)

根据documented behaviour 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()

1 个答案:

答案 0 :(得分: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)
    ]);
  });
});