Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
955 views
in Technique[技术] by (71.8m points)

angularjs - chai-as-promised tests don't work with $q promises

I'm trying to get chai-as-promised to work with $q promises with karma unit tests.

  svc.test = function(foo){
    if (!foo){
      // return Promise.reject(new Error('foo is required'));
      return $q.reject(new Error('foo is required'));
    } else {
      // get data via ajax here
      return $q.resolve({});
    }
  };


  it.only('should error on no foo', function(){
    var resolvedValue = MyServices.test();
    $rootScope.$apply();
    return resolvedValue.should.eventually.be.rejectedWith(TypeError, 'foo is required');
  });

The unit test just times out. I am not sure what I'm doing wrong here to get the promise to resolve properly. It seems to be an issue with using $q -- when I use native Promise.reject() it works fine.

I filed a ticket here, but nobody seems to be responding: https://github.com/domenic/chai-as-promised/issues/150

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The way chai-as-promised expects to modify promise assertions is transferPromiseness method.

By default, the promises returned by Chai as Promised's assertions are regular Chai assertion objects, extended with a single then method derived from the input promise. To change this behavior, for instance to output a promise with more useful sugar methods such as are found in most promise libraries, you can override chaiAsPromised.transferPromiseness.

For Angular 1.3+ support, $q promises can be duck-typed by $$state property, so native promises won't be affected:

chaiAsPromised.transferPromiseness = function (assertion, promise) {
  assertion.then = promise.then.bind(promise);

  if (!('$$state' in promise))
    return;

  inject(function ($rootScope) {
    if (!$rootScope.$$phase)
      $rootScope.$digest();
  });
};

chaiAsPromised chains each asserted promise with then. Even if the promise is settled, the rest of the chain still requires the digest to be triggered manually with $rootScope.$digest().

As long as the spec contains no asynchronous code, it becomes synchronous, no promise is required to be returned:

it('...', () => {
  ...
  expect(...).to.eventually...;
  expect(...).to.eventually...;
});

And is equal to mandatory $rootScope.$digest() after each set of eventually assertions/expectation when transferPromiseness wasn't set:

it('...', () => {
  ...
  expect(...).to.eventually...;
  expect(...).to.eventually...;
  $rootScope.$digest();
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...