2013-05-20 59 views
1

我有一种服务,有大约十几种方法挂起它。我正在设置我的第一轮单元测试。这里是一个的工作一个简单的例子:

it('should have a working getter/setter for SummaryLayoutBn', function() { 
    layoutService.setCurrentSummaryLayoutBn('TEST_BN'); 
    summaryLayoutBn = layoutService.getCurrentSummaryLayoutBn(); 
    expect(summaryLayoutBn).toEqual('TEST_BN'); 
}); 

然后我用$ httpBackend返回一些嘲笑JSON数据:

it('should have a working getLayout function', function() { 

    $httpBackend.expectGET('/b/json/layout/TEST_BN').respond(defaultSystemLayout); 

    expect(layoutCtrlScope.layoutModel.layout).toBeUndefined(); 

    layoutCtrlScope.loadLayoutFromBn('TEST_BN'); 

    $httpBackend.flush(); 

    expect(layoutCtrlScope.layoutModel.layout).toBe(defaultSystemLayout) 
}); 

这是工作,但我不再打电话给我服务,我在调用该服务的控制器中调用一个函数。这是正确的方法吗?它允许我测试layoutCtrlScope.layoutModel.layout,但感觉像是控制器的测试。

这里是布局服务

getLayout: function (bn) { 
    utilService.showLoading(); 
    var url = baseUrl.generateUrl(baseUrl.layout, bn); 
    return $http.get(url). 
     success(function (data, status, headers, config) { 
      utilService.hideLoading(); 
     }). 
     error(function (data, status, headers, config) { 
      errorHandlingService.handleGenericError(status); 
     utilService.hideLoading(); 
     }); 
} 

而且控制器功能:

$scope.loadLayoutFromBn = function (layoutBn) { 
     var layout = layoutService.getLayout(layoutBn); 
     layout.then(function (data) { 
      $scope.layoutModel.layout = data.data; 
     }); 
} 

回答

0

理想情况下,你应该能够单元测试你的服务的功能,而无需使用任何方法,你控制器。

看着你getLayout服务功能,好像你可以捕捉到这样的事情...

describe('getLayout', function() { 
    describe('before the request', function() { 
    it('shows the loading', function() { 
     // assert that utilService.showLoading() has been called 
    }) 
    }) 

    describe('on success', function() { 
    it('hides the loading', function() { 
     // assert that utilService.hideLoading() has been called 
    }) 
    }) 

    describe('on failure', function() { 
    it('hides the loading', function() { 
     // assert that utilService.hideLoading() has been called 
    }) 

    it('handles errors based on the status', function(){ 
     // assert that the generic error handler has been called with the expected status 
    }) 
    }) 
}) 

你$ httpBackend期待一个GET请求将确保该URL是正确生成,然后你只需要在成功/失败情况下返回不同的回应。在第一个断言中,你甚至不需要清理任何请求。

相关问题