【问题标题】:How to test an angular service function nested promises?如何测试角度服务功能嵌套的承诺?
【发布时间】:2017-06-01 00:52:15
【问题描述】:

这就是我的服务的样子

TestService.initializeDefaults = function() {
        var qPromise = $q.defer();
        $q.all({localResource : localResource.fetch(),
                item : itemResource.fetch()}).then(function(directories){

            //stuff happens with directories
            $q.all({
                thing1 : anotherThingFetch.fetch(),
                thing2: someThingFetch.fetch(),
                thing3: thingFetch.fetch()
            }).then(function(funData) {
                //stuff happens with the data

                preventiveServicesService.fetch().then(function() {

                    //stuff happens
                });

            });
        }.bind(this));
        return qPromise;
    };

我正在尝试使用 karma 来测试此 initializeDefaults 方法中的所有函数是否已运行。这意味着基本上所有的提取都发生了。到目前为止,这是我在测试中所拥有的:

it("should initialize defaults (Scenario 1)", function() {

            service.initializeDefaults();

            rootScope.$apply();

            expect(localResourceMock.fetch).toHaveBeenCalledWith();
            expect(itemResourceMock.fetch).toHaveBeenCalledWith();

【问题讨论】:

    标签: javascript angularjs testing jasmine karma-runner


    【解决方案1】:

    嗯,有两种方法可以解决这个问题。

    1) 使用 $httpBackend:对你正在制作的所有 $http 类使用类似 $httpBackend.expectGET('url1').respond(200, {}) 之类的东西。然后调用 $httpBackend.flush() 它也应该执行所有嵌套的 Promise。 缺点:这将执行被调用方法中的所有逻辑。

    2) 使用 Jasmine 间谍:执行以下操作:

    let deferred = $q.defer();
    deferred.resolve(/*data you expect the promise to return*/); 
    spyOn(localResourceMock, 'fetch').and.returnValue(deferred.promise);
    spyOn(itemResource, 'fetch').and.returnValue(deferred.promise);
    
    spyOn(anotherThingFetch, 'fetch').and.returnValue(deferred.promise);
    /*And so on for all methods being invoked*/
    
    // Invoke the method
    service.initializeDefaults();
    
    // Trigger digest cycle
    rootScope.$digest();
    
    /*Expect all the spies to have been called*/
    expect(anotherThingFetch.fetch).toHaveBeenCalledWith(); // will now pass
    

    其中任何一个都可以。你的来电。 干杯。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-21
      • 1970-01-01
      • 2014-06-17
      • 1970-01-01
      • 1970-01-01
      • 2017-02-27
      相关资源
      最近更新 更多