你如何模拟作为函数的Angular服务?

dnc*_*253 2 javascript unit-testing jasmine angularjs

我们有一个我们称之为a的东西CORShttpService,它基本上是一个服务器的包装器$http,但封装了我们需要的一些CORS功能.我现在正在为CORShttpService注入其中的服务编写一些测试.此服务的代码如下:

CORShttpService({method: requestMethod, url: getUrl(path), data: data}).
    success(function(data, status, headers) {
        //do success stuff
    }).
    error(function(data, status, headers) {
       //do error stuff
    });
Run Code Online (Sandbox Code Playgroud)

我想嘲笑电话CORShttpService,但我不知道如何去做.我正在使用Jasmine,它的spyOn功能需要一个对象来模拟对象上的函数.我CORShttpService没有任何对象,所以我不知道怎么去嘲笑它.是的,我可以$httpBackend用来模拟最终设置的请求CORShttpService,但我不希望它首先进入该服务.我想隔离单元测试并简单地模拟外部调用.有什么方法可以嘲笑这个只是一个功能的服务吗?

dnc*_*253 7

正如我对此的考虑更多,该$httpBackend服务确实提供了许多测试请求的功能.因为我CORShttpService基本上是一个包装器$http,所以我决定我可能获得最大的收益,如果我做了CORShttpService简单的模拟实现$http实现.使用此文档来帮助我,我的规范中包含以下内容:

beforeEach(module(function($provide) {
    $provide.provider('CORShttpService', function() {
        this.$get = function($http) {
            return $http;
        };
    });
}));
Run Code Online (Sandbox Code Playgroud)

因此,我想要CORShttpService注入的任何服务现在基本上只需要$http注入,因此允许我使用所有$httpBackend功能而无需担心CORShttpService自身中的额外功能.

这适用于我的具体情况,但就模拟服务只是一个函数的一般解决方案而言,jasmine.createSpy如zbynour的答案中提到的那样,可能会完成同样的事情.就像是:

beforeEach(module(function($provide) {
    $provide.provider('MyService', function() {
        this.$get = function() {
            return jasmine.createSpy("myService");
        };
    });
}));
Run Code Online (Sandbox Code Playgroud)