【发布时间】:2016-12-23 13:43:41
【问题描述】:
我是 AngularJS 和单元测试的新手,
我正在测试一个按所选类别更改的列表。
测试通过了,但前提是我使用 httpBackend.expectGET(),它期望来自“getSomethingElse”方法的 XMLHttpRequest。
我也尝试使用 scope.$digest() 但我得到了相同的结果......
控制者:
app.controller('mainCtrl', ['$scope', 'myService', function($scope,
myService) {
$scope.category = null;
myService.getSomethingElse().then(function(res) {
$scope.somethingElse = res.data;
});
$scope.$watch('category', function() {
if ($scope.category !== null) {
myService.getListByCat($scope.category.name).then(function(res) {
$scope.list = res.data;
});
}
else {
myService.getLongList().then(function(res) {
$scope.list = res.data;
});
}
});
}]);
服务:
app.service('myService', ['$http', function($http) {
this.getListByCat = function(category) {
return $http.get('getting-list?cat=' + category);
};
this.getLongList = function() {
return $http.get('getting-long-list');
};
this.getSomethingElse = function() {
return $http.get('getting-something-else');
};
}]);
测试
describe('Testing mainCtrl', function() {
var scope, ctrl;
var myServiceMock = {
getSomethingElse: jasmine.createSpy().and.returnValue(1),
getListByCat: jasmine.createSpy().and.returnValue(2)
};
beforeEach(function() {
module('app');
inject(function($rootScope, $controller) {
scope = $rootScope.$new();
ctrl = $controller('mainCtrl', {
$scope: scope,
myService: myServiceMock
});
});
});
it('should update the list by selected category', function() {
expect(scope.category).toBeNull();
expect(scope.list).toBeUndefined();
scope.category = {
id: 1,
name: 'Jobs'
};
scope.$apply();
expect(myServiceMock.getSomethingElse).toHaveBeenCalled();
expect(myServiceMock.getListByCat).toHaveBeenCalled();
});
});
【问题讨论】:
-
单元测试一个一个的测试单元,这样我们就知道哪一个坏了。应该有两个测试。一个人用模拟的 httpBackend 响应测试 myService。另一个使用模拟的 myService 测试控制器。顺便说一句,在基于 Promise 的方法中接受回调不是一个好习惯。更可靠的方法是返回一个承诺。
-
感谢您的建议,我更改了服务方法以返回承诺。关于测试,你能给我举个例子来说明你将如何编写这些测试吗?我应该从返回承诺的方法中得到什么?我应该如何使用模拟服务测试控制器?
-
这是这种分离的一个例子,我想它非常接近你的情况。 stackoverflow.com/a/39023684/3731501
-
我根据您的示例编辑了测试。现在我收到此错误“未定义不是对象(正在评估'myService.getSomethingElse')”
-
我做错了什么?
标签: angularjs unit-testing jasmine