一尘不染

在Jasmine 2.0中测试AngularJS Promise

angularjs

我一直在努力围绕Jasmine 2.0和AngularJS的承诺。我知道:

如何在Jasmine 2.0中使用新的异步语法测试AngularJS Promise?


阅读 215

收藏
2020-07-04

共1个答案

一尘不染

致电后promise.resolve()

  • 致电$timeout.flush()。这将强制进行摘要循环并传播承诺解决方案
  • 致电done()。告诉Jasmine异步测试已经完成

这是一个示例( 有关Plunker的演示 ):

describe('AngularJS promises and Jasmine 2.0', function() {
    var $q, $timeout;

    beforeEach(inject(function(_$q_, _$timeout_) {
        // Set `$q` and `$timeout` before tests run
        $q = _$q_;
        $timeout = _$timeout_;
    }));

    // Putting `done` as argument allows async testing
    it('Demonstrates asynchronous testing', function(done) {
        var deferred = $q.defer();

        $timeout(function() {
            deferred.resolve('I told you I would come!');
        }, 1000); // This won't actually wait for 1 second.
                  // `$timeout.flush()` will force it to execute.

        deferred.promise.then(function(value) {
            // Tests set within `then` function of promise
            expect(value).toBe('I told you I would come!');
        })
        // IMPORTANT: `done` must be called after promise is resolved
        .finally(done);

        $timeout.flush(); // Force digest cycle to resolve promises
    });
});
2020-07-04