angularjs - 我将如何使用 AngularJs 模拟 Jasmine 的 then() 响应测试

标签 angularjs unit-testing testing jasmine karma-jasmine

这是我的代码

 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() 中的什么地方完成,如果是这样,我需要测试返回的响应是否为假和真。

做了以下修改:

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');
  });


});

现在出现以下错误:错误:意外请求:GET http://localhost:34327/guest//IsAdmin

最佳答案

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

spyOn(guestService, 'isUserAdmin').andReturn($q.when(true));

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

spyOn(guestService, 'isUserAdmin').andReturn($q.when(false));

测试错误路径:

spyOn(guestService, 'isUserAdmin').andReturn($q.reject());

阅读$q documentation .

确保在需要时调用 $rootScope.$apply() 以实际解决/拒绝 promise 。

例如:

// 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

关于angularjs - 我将如何使用 AngularJs 模拟 Jasmine 的 then() 响应测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32351870/

相关文章:

javascript - ng 重复后 AngularJS 插件初始化

python - 如何模拟嵌套函数?

django:来自 django.contrib.auth 的测试失败

c# - 如何通过编程/编码实现webservice测试自动化

javascript - 为 Typescript 中的 Angular Directive(指令)错误键入服务对象

javascript - AngularJS - 验证输入字段的动态模式

字符串的Javascript数组转换为对象数组

c# - 迭代器 block 的奇怪测试覆盖率结果,为什么不执行这些语句?

python - 测试依赖时间的方法

php - 如何在 phpspec 测试中使用 laravel session