【问题标题】:How to test a service in Angular with $q如何使用 $q 在 Angular 中测试服务
【发布时间】:2014-09-24 12:12:27
【问题描述】:

我有一个简单的服务:

.factory('list', function($q, $timeout) {
    return {
        get: function() {
            var dfd = $q.defer();

            $timeout(function () {
                dfd.resolve(['label1', 'label2']);
            }, 10);

            return dfd.promise;
        }
    };
});

并想测试它。所以我创建了:

describe('list', function() {

    var list, labels;

    beforeEach(module('app'));
    beforeEach(inject(function($q, _list_) {
       list = _list_;

       spyOn(list, 'get').and.callThrough();

       list.get().then(function(result) {
           labels = result;
       });
    }));

    describe('getting list of labels', function() {

        it('should return list of labels', function() {
            expect(labels).not.toBe(undefined);
            expect(Array.isArray(labels)).toBeTruthy();
        });

     });

});

但问题是,即使 service 中的 get 方法返回 promise,then 函数中的回调也没有执行。难道我做错了什么?我在 Jasmine 中读到了 callFake 方法,但老实说,我没有看到使用它的意义。你能解释一下使用它有什么好处吗?顺便说一句,我有 Jasmine 2.0 和带有 angular-mocks 的最新 angular。

【问题讨论】:

  • beforeEach 将函数作为参数。如果您希望它是异步的,那么该函数应该接受一个回调函数。检查这个问题stackoverflow.com/q/25598353/1197333
  • 我不太明白它应该如何工作。我现在有beforeEach(function(done)),但我应该什么时候打电话?在then 内部(不起作用)还是在外部(两者都没有)?

标签: javascript angularjs unit-testing testing jasmine


【解决方案1】:

答案很简单,我忘记了。由于我使用了 $timeout,我应该在之后致电 flush

【讨论】:

    猜你喜欢
    • 2015-07-07
    • 2014-09-04
    • 1970-01-01
    • 2013-03-29
    • 1970-01-01
    • 2017-08-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多