【发布时间】:2014-09-25 14:29:10
【问题描述】:
我正在尝试对我在 jasmine 测试框架中编写的一些 Angular js 控制器进行单元测试。我已经完成所有设置,以便能够创建控制器实例并传入模拟服务。
但是,我有几行代码在页面加载时运行。
$scope.tags = [];
$scope.noData = false;
$scope.generateSearchResults = function(input){
searchAPI.executeSearch(input).then(function(res){
$scope.tags = res.data;
});
};
//does some post processing on tags
$scope.checkNumberOfResults = function(){
if($scope.tags.length < 1){
$scope.noData = true;
}
}
//this is the code that runs when the page loads.. normally I want this behavior,
//but for my jasmine unit tests, I don't want the controller running any code on
//instantiation
$scope.$watch('$viewContentLoaded', function(){
$scope.searchQuery = $routeParams.query; //grabs from the url
$scope.generateSearchResults($scope.searchQuery){
.then(function(res){
$scope.checkNumberOfResults();
});
});
因此,如果您知道,当页面加载时,我想从 url 中获取查询字符串,然后显示搜索结果。问题是,我不希望这段代码在测试时运行,至少不是为了我的单元测试。也许当我做一些集成测试时,我希望能够模拟页面加载,但现在,我想在控制器中对我的其他一些功能进行单元测试,而不必调用搜索 API 服务。.
这有意义吗?有人对在哪里进行此操作有任何建议吗?
【问题讨论】:
标签: angularjs unit-testing controller jasmine onload