在测试中调用 $rootScope 的 $apply/$digest 方法的正确时机
Correct moment to call $rootScope's $apply/$digest method in a test
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
显示的 example 是不同的情况。
它使用
expect(resolvedValue).toEqual(123);
不涉及承诺的断言。
另一方面,
state.should.eventually.be.equal('abcc')
使用 chai-as-promised
进行断言。它在幕后将 state
与 then
链接起来以获取值并声明它。 $q
承诺链仅在摘要上执行。这就是为什么 $rootScope.$digest()
在 eventually
断言之后是必要的。
另请参阅 this answer,了解有关如何使用 chai-as-promised
测试 Angular 的更多详细信息。
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
显示的 example 是不同的情况。
它使用
expect(resolvedValue).toEqual(123);
不涉及承诺的断言。
另一方面,
state.should.eventually.be.equal('abcc')
使用 chai-as-promised
进行断言。它在幕后将 state
与 then
链接起来以获取值并声明它。 $q
承诺链仅在摘要上执行。这就是为什么 $rootScope.$digest()
在 eventually
断言之后是必要的。
另请参阅 this answer,了解有关如何使用 chai-as-promised
测试 Angular 的更多详细信息。