我有一项服务,其中包含大约十几种方法。我正在进行第一轮单元测试。这是一个简单的例子:
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 :(得分: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
})
})
})
期望GET请求的$ httpBackend将确保正确生成URL,然后您只需要在成功/失败上下文中返回不同的响应。在第一个断言中,您甚至不必刷新任何请求。