gpt4 book ai didi

service - Karma/Jasmine 使用依赖项对 AngularJS 服务进行单元测试

转载 作者:行者123 更新时间:2023-12-02 10:36:48 25 4
gpt4 key购买 nike

我是一名新手程序员,对 AngularJS 和单元测试实践都很陌生。我花了几个小时试图找到解决方案,但我变得越来越困惑。如果有人能指出我正确的方向,我将不胜感激。我会尽可能地进行描述。

情况是这样的:

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

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

这是我所知道的:

$httpBackend 模拟是我需要能够对 API 进行虚假调用的东西,它提供了预期某些请求并返回指定结果的功能。

我需要测试真实的服务 A 并注入(inject)我为服务 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}"
]

最佳答案

那么您是说您知道如何使用 $provide/Jasmine spy 执行此操作,并且正在寻找替代方案?我主要使用 $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 请求,你只需要使用 $injector 服务来抓取 $httpBackend,然后对其调用 .when(...) 来进行设置,a la http://docs.angularjs.org/api/ngMock.$httpBackend

关于service - Karma/Jasmine 使用依赖项对 AngularJS 服务进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17327186/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com