angularjs – chai-as-promise测试不适用于$q promises

前端之家收集整理的这篇文章主要介绍了angularjs – chai-as-promise测试不适用于$q promises前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在努力让chai-as-promised与$q承诺一起使用karma单元测试.
  1. svc.test = function(foo){
  2. if (!foo){
  3. // return Promise.reject(new Error('foo is required'));
  4. return $q.reject(new Error('foo is required'));
  5. } else {
  6. // get data via ajax here
  7. return $q.resolve({});
  8. }
  9. };
  10.  
  11.  
  12. it.only('should error on no foo',function(){
  13. var resolvedValue = MyServices.test();
  14. $rootScope.$apply();
  15. return resolvedValue.should.eventually.be.rejectedWith(TypeError,'foo is required');
  16. });

单元测试只是超时了.我不确定我在这里做错了什么来得到正确解决的承诺.使用$q似乎是一个问题 – 当我使用本机Promise.reject()时,它工作正常.

我在这里提交了一张票,但似乎没有人回应:
https://github.com/domenic/chai-as-promised/issues/150

您需要更改测试中的执行顺序.具有chai-as-promise的异步任务需要在预期之前发生.
  1. it('does not work',() => {
  2. $timeout.flush();
  3. expect(myAsyncTask()).to.eventually.become('foo');
  4. })
  5.  
  6. it('does work',() => {
  7. expect(myAsyncTask()).to.eventually.become('foo');
  8. $timeout.flush();
  9. })

在刷新异步任务队列之前,需要启动对异步任务的调用.

另外,不要使用$rootScope.$digest.这可能会产生其他副作用,这些副作用在您的测试中是不可取的.

$timeout.flush是你正在寻找的.

https://docs.angularjs.org/api/ngMock/service/ $超时

让您的特定测试工作:

  1. it('should error on no foo',function(){
  2. MyServices.test().should.eventually.be.rejectedWith(TypeError,'foo is required')
  3. $rootScope.$apply();
  4. });
  5.  
  6. it('should pass on foo',function(){
  7. MyServices.test('foo').should.eventually.become({});
  8. $rootScope.$apply();
  9. }

TL;博士

  1. it('async test',() => {
  2. setup();
  3. expect();
  4. execute();
  5. })
  6.  
  7. it('sync test',() => {
  8. setup();
  9. execute();
  10. expect();
  11. })

鉴于发表的评论

Should it be mentioned that it is unethical to downvote ‘rival’ answers on the question you’re answering?

很公平.我认为答案是误导性的,因为没有必要进行额外的设置以使得使用Angular的承诺可以在不必处理完成的回调的情况下使用它. Fwiw,我会继续尝试撤销所说的downvote,并对此有道德.

The OP has no signs of timeout in his code and doesn’t state that the task is asynchronous. $rootScope.$digest() has no side effects in specs when called outside of scope digest. The reason why it is not recommended in production is because it doesn’t have the safeguards that $apply has.

$rootScope.$digest实际上与$rootScope相同.$apply(和$scope.$适用于此事). source

$timeout.flush也将刷新非基于$timeout的函数.它不是基于$timeout的功能所独有的.

Plunker展示它如何工作™:
plunker

猜你在找的Angularjs相关文章