【问题标题】:Correct moment to call $rootScope's $apply/$digest method in a test在测试中调用 $rootScope 的 $apply/$digest 方法的正确时机
【发布时间】:2017-01-03 13:35:15
【问题描述】:

Angular 测试文档显示了一个 test sample,其中 $apply 在测试断言之前被调用。我尝试做同样的事情,但我的测试无法正常工作。第一个应该中断的代码可以工作……看来我的断言没有运行。第二个代码,我的测试有效,但它与文档不同(我更喜欢这种风格)。

第一:

it('tests angular promises', function() {
    getABC = function() {
        return $q((resolve, reject) => {
            resolve('abc');
        });
    };

    var state = getABC()

    $rootScope.$apply()
    // assertions come after $apply call as in documentation: doesn't work.
    state.should.eventually.be.equal('abcc') 
})

------
✓ tests angular promises


1 passing (78ms)

第二

it('tests angular promises', function() {
    getABC = function() {
        return $q((resolve, reject) => {
            resolve('abc');
        });
    };

    var state = getABC()

    state.should.eventually.be.equal('abcc')
    // assertions come before  $apply call: works
    $rootScope.$apply()
})

------
1 failing

1) tests angular promises:

  AssertionError: expected 'abc' to equal 'abcc'
  + expected - actual

  -abc
  +abcc

【问题讨论】:

    标签: angularjs promise mocha.js chai chai-as-promised


    【解决方案1】:

    显示的example 是不同的情况。

    它使用

    expect(resolvedValue).toEqual(123);
    

    不涉及承诺的断言。

    另一方面,

    state.should.eventually.be.equal('abcc')
    

    使用chai-as-promised 进行断言。它在后台将statethen 链接起来以获取值并对其进行断言。而$q 承诺链仅在摘要上执行。这就是为什么在eventually 断言之后需要$rootScope.$digest()

    有关如何使用 chai-as-promised 测试 Angular 的更多详细信息,另请参阅 this answer

    【讨论】:

      猜你喜欢
      • 2014-09-28
      • 1970-01-01
      • 2013-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-12
      • 1970-01-01
      • 2016-06-16
      相关资源
      最近更新 更多