【发布时间】:2015-04-19 17:17:20
【问题描述】:
假设我有一个这样的控制器:
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?
});
});
顺便说一句,如果该解决方案也适用于服务和指令中的本地函数,那就太好了。
相关问题:
【问题讨论】:
-
从哪里调用 getOldestNews?如果没有入口点,为什么会存在?
-
@Ricconnect 我在 sn-p 中添加了一些上下文,如果还不清楚,请告诉我。
-
NewsFeedService 上有
getOldestNewsItem或getOldestNewsItemStamp方法不是更合乎逻辑吗?我问这个是因为,如果你想测试私有方法,这在大多数情况下表明设计不好。 -
好,好点子!所以
NewsService.getOldestNews应该接受一个论点,一个新闻项目的集合?我想知道什么更理想:在服务或$scope中存储项目。将这些存储在服务本身似乎不是一个好主意,对吧? -
我也想知道它是否真的值得成为
NewsService的方法,因为它可能只对这个特定的控制器有用。
标签: angularjs karma-runner karma-jasmine