繁体   English   中英

测试使用另一个使用$ http的服务的角度服务

[英]Testing an angular service that uses another service that uses $http

我已经编写了两个角度服务。

一个叫做“ 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)我仍然对角度不了解,所以我不知道我的诺言设置是否完全达到标准。 除了预先输入内容外,我还有其他用于searchAPI请求构建功能的用途,这就是为什么我想将请求构建器/启动器变成自己的独立对象。

2)我需要帮助测试此typeAhead服务。 对于单元测试,我如何确保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块内的代码没有被警告,因此我的诺言一定不能解决。

您对Promise的用法听起来不错,并且与应有的外观相当。 那很好。

至于你的问题-我可能会模拟它以反映原始API-模拟具有静态值的$q.when您可以使用$q.when

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

$q.when将外部(非Angular)诺言或简单值转换为Angular诺言-在这种情况下为数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM