Angularjs 如何在角度控制器内测试局部功能?
假设我有一个控制器,如:Angularjs 如何在角度控制器内测试局部功能?,angularjs,karma-runner,karma-jasmine,Angularjs,Karma Runner,Karma Jasmine,假设我有一个控制器,如: angular .module("app", []) .controller("NewsFeedController", [ "$scope", "NewsFeedService", function ($scope, NewsFeedService) { $scope.news = [ { stamp: 1 }, {
angular
.module("app", [])
.controller("NewsFeedController", [
"$scope",
"NewsFeedService",
function ($scope, NewsFeedService) {
$scope.news = [
{ stamp: 1 },
{ stamp: 9 },
{ stamp: 0 }
];
$scope.onScroll = function () {
/*
might do some stuff like debouncing,
checking if there's news left to load,
check for user's role, whatever.
*/
var oldestStamp = getOldestNews().stamp;
NewsFeedService.getOlderThan(oldestStamp);
/* handle the request, append the result, ... */
};
function getOldestNews () {
/* code supposed to return the oldest news */
}
}
]);
getOldestNews
声明为本地函数,因为在$scope
中没有必要公开它
我该怎么处理呢?如何实际测试此函数
describe("NewsFeedController", function () {
beforeEach(module("app"));
var $controller, $scope, controller;
beforeEach(inject(function (_$controller_) {
$controller = _$controller_;
$scope = {};
controller = $controller("NewsFeedController", { $scope: $scope });
}));
it("should return the oldest news", function () {
// How do I test getOldestNews?
});
});
顺便说一下,如果该解决方案也适用于服务和指令中的本地功能,那就太好了
相关问题:
describe("NewsFeedController", function () {
beforeEach(module("app"));
var $controller, $scope, controller;
var newsFeedServiceMock = jasmine.createSpyObj('NewsFeedService', ['getOlderThan']);
beforeEach(inject(function (_$controller_) {
$controller = _$controller_;
$scope = {};
controller = $controller("NewsFeedController", { $scope: $scope, NewsFeedService : newsFeedServiceMock });
}));
it("should return the oldest news", function () {
$scope.news = [
{ stamp: 76 },
{ stamp: 4 },
{ stamp: 83 }
];
$scope.onScroll();
expect(newsFeedServiceMock.getOlderThan).toHaveBeenCalledWith(83);
});
});
这样,您就可以检查onScroll方法是否执行了正确的行为,而无需检查私有方法。您只想测试公共方法,因此当您想创建私有方法来分离逻辑时,您可以灵活使用,而无需更改测试。从何处调用getOldestNews?如果没有入口点,它为什么存在?@Ricconnect我在代码段中添加了一些上下文,如果还不清楚,请告诉我。如果NewsFeedService上有
getOldestNewsItem
或getOldestNewsItemStamp
方法,这不是更符合逻辑吗?我这样问是因为,如果你想测试私有方法,大多数时候这是一个糟糕设计的迹象。耶,好的观点!所以newservice.getOldestNews
应该接受一个参数,一组新闻项?我想知道什么更理想:在服务或$scope
中存储项目。将这些存储在服务本身似乎不是一个好主意,对吗?我还想知道它是否真的值得成为一个新闻服务的方法,因为它可能只对这个特定的控制器有用。如果pvt函数有足够的逻辑怎么办..我是否可以在不更改为public func的情况下测试它们?如果private函数有那么多逻辑,您可以将该私有函数移动到单独的角度服务。在单元测试中测试私有函数通常是一种不好的做法。但是,如果我想在单元测试中测试私有函数呢?有没有办法在单元测试中测试私有函数?没有,不可能在单元测试中测试私有函数,因此您需要公开控制器内的函数或将其作为公共函数移动到另一个服务