2014-12-02 106 views
1

我有两个我写的角度服务。

一个名为“searchAPI”的实质上接受用户输入,形成弹性搜索查询,然后通过$ http.get调用将其关闭。

//searchAPI 

service = { 
    executeSearch: function(input, resultsPerPage, pageNumber){ 
     request = // some well tested logic that I know works to create a query string 
     return $http.get(request); 
    } 
} 

另一个叫做typeAhead,它使用我的searchAPI获取typeAhead结果列表。

//typeAhead 

service = { 

    typeAheadContent: [], 

    buildTypeAheadContent: function(input){ 
     return searchAPI.executeSearch(input, 10, 1).then(function(res){ 
      for(var i = 0; i < res.length; i++){ 
       service.typeAheadContent.push(res[i]); 
      } 
     }); 
    }, 

    getTypeAheadResults: function(input){ 
     return service.buildTypeAheadContent(input).then(function(){ 
      return service.typeAheadContent; 
     });  
    } 
}; 

这里有几件事。

1)我仍然得到角度的挂钩,所以我不知道我的诺言设置是否完全达到标准。除了我的typeahead之外,我还有其他一些用于searchAPI请求构建功能的用途,这就是为什么我想让请求构建器/ firer成为它自己独立的东西。

2)我需要帮助测试这种类型的前端服务。对于单元测试,我如何确保searchAPI实际上不会到我的后端,而是返回一些模拟数据或模拟诺言或其他东西?如果我能做到的话,这样的事情会很理想。

searchAPI.executeSearch = function(){ 
    return [ 
     'item1', 
     'item2', 
     'item3' 
    ] 
} 

我想在我的茉莉花测试做这样的事情,但以这种方式嘲笑它,我不调用一个承诺,只设置一个返回值。

有人可以帮我开始我的设置并嘲笑一些承诺吗?

////编辑////

这是我在我的茉莉花测试每个功能之前。

var searchAPI, typeAhead; 
beforeEach(inject($rootScope, $injector, $q) 
{ 
    typeAhead = $injector.get('typeAhead'); 
    searchAPI = $injector.get('searchAPI'); 
    searchAPI.executeSearch = function(input, resultsPerPage, pageNumber){ 

     // this is being alerted just fine 
     alert("Inside mock"); 
     return $q.when([ 
      'item1', 'item2', 'item3' 
     ]); 
    } 
    $rootScope.$digest(); 
})); 

it('should construct typeahead stuff', function(){ 

    searchAPI.executeSearch("hello", 10, 1).then(function(res){ 

     //this is not being alerted 
     alert(res); 
    }); 
    typeAhead.buildTypeAheadContent("test"); 
}); 

所以我包含了一些东西来帮助调试。警告“Inside Mock”的代码行确实被警告,所以我知道我分配给executeSearch的模拟事件正在正确设置。然而,.then块内部的代码没有被警告,所以我的承诺一定不能得到解决或什么...

回答

1

你对Promise的使用听起来很好,并达到它应该看起来的样子。那很好。

至于你的问题 - 我可能会嘲笑它反映原始API - 到模拟的承诺与静态值 - 您可以使用$q.when

searchAPI.executeSearch = function(){ 
    return $q.when([ 
     'item1', 
     'item2', 
     'item3' 
    ]); 
}; 

$q.when转换外国(非角)的承诺或对Angular承诺的简单价值 - 在这种情况下是您的数组。

+0

感谢您的回复。我会在午饭后试试这个,看看它是否符合我的需求,然后你会接受:) – Zack 2014-12-02 18:05:27

+0

这仍然不是我想要的不幸。 )。然后(函数(RES){警报(RES);}); 没有任何提示。 – Zack 2014-12-03 15:43:55

+0

尝试在假设你没有使用1.3之后尝试添加'$ rootScope.digest()'。我不知道我是否在使用1.3 – 2014-12-03 15:54:57