栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在业力/茉莉花测试中模拟角度服务/承诺

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在业力/茉莉花测试中模拟角度服务/承诺

因此,如果您的服务是否按预期进行响应,那么您想测试一下吗?然后,您宁愿在服务上对此进行测试。基于单元测试承诺的方法可能如下所示:

var mapService, $httpBackend, $q, $rootScope;beforeEach(inject(function (_mapService_, _$httpBackend_, _$q_, _$rootScope_) {  mapService = mapService;  $httpBackend = _$httpBackend_;  $q = _$q_;  $rootScope = _$rootScope_;  // expect the actual request  $httpBackend.expect('GET', '/onmap/rest/map/uuid?editor=true');  // react on that request  $httpBackend.whenGET('/onmap/rest/map/uuid?editor=true').respond({    success: {      elements: [1, 2, 3]    }  });}));

如您所见,您无需使用

$injector
,因为您可以直接注入所需的服务。如果您想在整个测试过程中使用正确的服务名称,则可以在它们的前面加上前缀和后缀“
_”,这样
inject()
可以聪明地识别出您要使用的服务。我们还
$httpBackend
为每个
it()
规格设置了模拟程序。并且我们进行设置
$q
$rootScope
进行后续处理。

这是测试服务方法是否返回承诺的方法:

it('should return a promise', function () {  expect(mapService.getMapUuid('uuid', true).then).toBeDefined();});

由于promise始终具有

.then()
方法,因此我们可以检查此属性以查看它是否为promise(当然,其他对象也可以使用此方法)。

接下来,您可以测试您获得的具有适当价值的承诺。您可以进行设置以

deferred
明确解决。

it('should resolve with [something]', function () {  var data;  // set up a deferred  var deferred = $q.defer();  // get promise reference  var promise = deferred.promise;  // set up promise resolve callback  promise.then(function (response) {    data = response.success;  });  mapService.getMapUuid('uuid', true).then(function(response) {    // resolve our deferred with the response when it returns    deferred.resolve(response);  });  // force `$digest` to resolve/reject deferreds  $rootScope.$digest();  // make your actual test  expect(data).toEqual([something]);});

希望这可以帮助!



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/613925.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号