2013-06-26 46 views
5

我是一位非常新的AngularJS和单元测试实践的新手程序员。我花了数小时试图找到解决办法,但我越来越困惑。如果任何人都可以指出我正确的方向,我将不胜感激。我会尽量保持描述性。Karma/Jasmine Unit依赖性测试AngularJS服务

情况是这样的:

我已经创造了AngularJS服务(服务A)有一对夫妇的功能。每个函数都会向REST API发出$ http GET请求,并返回包含JSON数据的$ http promise对象。在这些函数中,通过实现另一个非常简单的服务(服务B)来构造URL,该服务已经作为服务A的依赖注入。我创建了服务B的模拟,以将其与所有依赖关联起来。这两种服务都是在名为“services”的同一模块内部定义的。在这种情况下,并不需要这种依赖,但我只想了解它是如何工作的。

使用Jasmine,我想为服务A构建一个单元测试,以确保它对API的请求被正确构建,并且可能返回正确的JSON数据。同时,我不希望任何真正的API调用。

这是我知道的:

$ httpBackend模拟是我需要的是能够使虚拟来电的API,它提供的功能,预计某些请求并返回指定的结果。

我需要测试真正的服务A并注入我创建的服务B的模拟。我知道有办法使用Jasmine Spies和$ provide来做到这一点。我也看到了使用sinon.js的例子,我不确定哪个是最好的方法。


我会在下面发布我的源代码,它是用CoffeeScript编写的。

服务A:

'use strict' 

angular.module("services") 
    .service("ServiceA", ["$http", "ServiceB", ($http, ServiceB) -> 

    #Uses underscore.js to set this default attribute 
    defaults = withCredentials:true 

    getVarset: (itemName, options={}) -> 
     options.method = "GET" 
     options.url = ServiceB.makeUrl("item/#{itemName}") 

     $http _.defaults(options, defaults) 

    getVarsets: (options = {}) -> 
     options.method = "GET" 
     options.url = ServiceB.makeUrl("items") 

     $http _.defaults(options, defaults) 

    getModelsForVarset: (itemName, options = {}) -> 
     options.method = "GET" 
     options.url = ServiceB.makeUrl("item/#{itemName}/prices") 

     $http _.defaults(options, defaults) 
    ]) 

服务B:

'use strict' 

angular.module('services') 
    .service 'ServiceB', [ -> 

    # Just return the string 
    # This service builds the real URL, but I've removed this 
    makeUrl: (Url) -> 
     "#{Url}" 
    ] 

回答

4

所以你是说你知道如何使用$提供/茉莉花间谍做到这一点,并正在寻找替代品?我主要只是使用$ provide/spy方法来进行嘲讽,到目前为止它对我来说确实很好。

类似:

beforeEach(function() { 

    // set up a default value for your mock 
    bMock = { 
     makeUrl: jasmine.createSpy('makeUrl() mock').andReturn('http://www....') 
    } 

    // use the $provide service to replace ServiceB 
    // with your mock 
    module('services', function($provide) { 
     $provide.value('ServiceB', bMock); 
    }); 

}); 

it('should do what its supposed to do', function() { 
    // test... 
}); 

那么,如果你想用$ httpBackend嘲笑在服务A的HTTP请求,你只需要使用$注射器服务抢$ httpBackend,然后调用。当(...)对它进行设置,一个la http://docs.angularjs.org/api/ngMock.$httpBackend

相关问题