测试AngularJS在Jasmine 2.0中的承诺

Tyl*_*ich 30 javascript jasmine angularjs

我一直试图围绕Jasmine 2.0和AngularJS承诺.我知道:

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

Tyl*_*ich 43

致电后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
    });
});
Run Code Online (Sandbox Code Playgroud)

  • upvoted,认真,只添加$ timeout.flush()修复我的规格.真的太糟糕了,这不是有据可查的...... (6认同)
  • 只想添加一个链接到K. Scott Allen关于您在此处使用的beforeEach注入技术的帖子:http://odetocode.com/blogs/scott/archive/2014/05/15/a-few-thoughts-on - 更好-单元测试换angularjs-controllers.aspx (2认同)