【问题标题】:How would I mimic testing then() response with Jasmine, using AngularJs我将如何使用 AngularJs 模仿 Jasmine 的 then() 响应测试
【发布时间】:2015-09-02 11:26:39
【问题描述】:

这是我的代码

 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。

做了以下修改:

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

【问题讨论】:

    标签: angularjs unit-testing testing jasmine karma-jasmine


    【解决方案1】:

    用真正的 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(),以便在需要时实际解决/拒绝承诺。

    例如:

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

    【讨论】:

    • 里面是什么?什么意思?
    • 我需要运行一个它('assertiont test'),它的响应为真,一个它的响应为假,所以我的问题是 spyOn 是否进入它()?
    • 如果你想测试所有的情况,那么是的,应该有 3 个测试,每个都监视服务并让它在测试中做你想做的事情。
    • 在 Jasmine 2.0 中是否已弃用 andReturn?
    • 是的。如果使用 jasmine 2,请使用 and.returnValue()jasmine.github.io/2.0/introduction.html
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-12
    • 2017-02-28
    • 1970-01-01
    • 1970-01-01
    • 2013-07-21
    • 1970-01-01
    相关资源
    最近更新 更多