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

kum*_*rsh 9 testing selenium mocha.js 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)
Run Code Online (Sandbox Code Playgroud)

根据记录的行为,当预期失败时,chai-as-promise应该将错误传递给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)
Run Code Online (Sandbox Code Playgroud)

#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)
Run Code Online (Sandbox Code Playgroud)

#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()
Run Code Online (Sandbox Code Playgroud)

小智 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)
    ]);
  });
});
Run Code Online (Sandbox Code Playgroud)

  • 只是想要指出,摩卡 - 承诺似乎现在似乎没有必要.根据https://github.com/domenic/mocha-as-promised摩卡1.18.0有内置的承诺支持.https://mochajs.org/上的文档似乎同意. (4认同)