首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我将如何模拟使用AngularJs测试茉莉花的()响应

我将如何模拟使用AngularJs测试茉莉花的()响应
EN

Stack Overflow用户
提问于 2015-09-02 11:26:39
回答 1查看 71关注 0票数 0

这是我的密码

代码语言:javascript
复制
 function guestDeviceManagerController(guestService, status) {
   vm.initState = function() {
     guestService.isUserAdmin(status.standardId).then(function(isAdmin) {
       vm.isAdmin = isAdmin;
       vm.template = vm.isAdmin ? vm.templates[0] : vm.templates[1];
     }, function() {
       //TODO: display user error
     });
   };
   vm.initState();
 }

我想知道如何模拟这个请求,在SpyOn()中应该在哪里完成它,如果是的话,我需要测试响应是否返回为false和true。

作了以下修改:

代码语言:javascript
复制
describe('guestDeviceManagerController Tests', function() {
  'use strict';
  var scope,
    controller,
    statusService,
    guestService,
    q;


  beforeEach(function() {
    module('mainApp');
    module('mobileDevicesModule');

    inject(function($rootScope, $controller, $q, _statusService_, _guestService_) {
      scope = $rootScope.$new();
      statusService = _statusService_;
      guestService = _guestService_;
      q = $q;

      controller = $controller('guestController', {
        $scope: scope,
        guestService: guestService
      });
    });

  });



  it('Assert view that should render for admin', function() {

    spyOn(guestService, 'isUserAdmin').and.returnValue(q.when(true));
    scope.$apply();
    controller.initState();

    expect(controller.template.url).toEqual('app/mobile-devices/guest/admin/guest.html');
  });


});

现在获得以下错误: error:意外请求:获取http://localhost:34327/guest//IsAdmin

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-09-02 11:29:30

要用真正的isAdmin结果测试成功路径:

代码语言:javascript
复制
spyOn(guestService, 'isUserAdmin').andReturn($q.when(true));

若要使用错误的isAdmin结果测试成功路径:

代码语言:javascript
复制
spyOn(guestService, 'isUserAdmin').andReturn($q.when(false));

要测试错误路径:

代码语言:javascript
复制
spyOn(guestService, 'isUserAdmin').andReturn($q.reject());

$q文档

请确保在需要时调用$rootScope.$apply()来实际解决/拒绝承诺。

例如:

代码语言:javascript
复制
// spy the service:
spyOn(guestService, 'isUserAdmin').andReturn($q.when(true));
// instantiate the controller:
$controller('guestDeviceManagerController');
// resolve/reject the promises. This will cause the callback functions to be called
$rootScope.$apply();
// now test that the callback has done what it's supposed to do
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32351870

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档