【问题标题】:Why does a failed assertion trigger a promise catch?为什么一个失败的断言会触发一个承诺捕获?
【发布时间】:2018-02-14 07:14:41
【问题描述】:

在为 Angular 应用程序编写单元测试时,我遇到了意想不到的结果。我能够将意外行为浓缩为示例测试。

then 块中的should.equal(true, false, 'should then') 断言失败似乎触发了 promise 的 catch 块。

describe.only('test', function () {
  var $q, $rootScope;
  beforeEach(function () {
    inject(function(_$q_, _$rootScope_) {
      $q = _$q_;
      $rootScope = _$rootScope_.$new();
    });
  });


  var stubService = sinon.stub(service, 'getPanel');

  it('shall...', function() {
    //1
    $q.when().then(function() {
      console.log('log then')
      should.equal(true, false, 'should then') //<---assertion fails
    }).catch(function() {
      console.log('log catch') //<--- why does this block run?
      should.equal(true, false, 'should catch')
    })
    $rootScope.$apply(); //wait for promises to finish

  });
});

当我运行这个测试时,输出是:

 LOG LOG: 'log then'
 LOG LOG: 'log catch'

  test
    ✗ shall...
  should catch: expected true to equal false

我预计:

LOG LOG: 'log then'

  test
    ✗ shall...
  should then: expected true to equal false

如果我使用这种风格,我会得到预期的结果:

$q.when().then(function() {
  console.log('log then')
  should.equal(true, false, 'should then')
}, function() {
  console.log('log catch')
  should.equal(true, false, 'should catch')
})

我公司的惯例是使用第一种样式,所以我想尽可能使用第一种样式。

【问题讨论】:

    标签: angularjs unit-testing mocha.js chai q


    【解决方案1】:

    对您观察到的行为的一种解释是,当条件不满足时,should.equal 断言实际上是 throws an error

    虽然您使用的是$q,但我相信这个documentation on Promise behaviour 仍然适用,强调我的:

    处理函数(onFulfilledonRejected)随后被异步调用(一旦堆栈为空)。调用 handler 函数后,如果 handler 函数: ... 抛出错误,则 then 返回的 Promise 将被拒绝,并以抛出的错误为值;

    因此,在您的情况下,should.equal 引发的错误会导致 catch 的代码块被执行,而拒绝值是引发的错误。

    【讨论】:

      猜你喜欢
      • 2012-05-21
      • 2013-11-25
      • 2019-08-20
      • 1970-01-01
      • 1970-01-01
      • 2017-08-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多