Return a promise in jasmine directive controller

丶灬走出姿态 提交于 2019-12-12 03:02:27

问题


In my unit test i need to return a promise so that my tests don't fail:

describe('refugeeRegister', function () {

  var controller, scope, rootScope, window;

  beforeEach(function () {
    module('refugeeHire');
    module("templates");
    module('refugeeHire.components.refugee_register', function ($provide) {
      $provide.service("authenticationService", function () {
        this.signup = jasmine.createSpy("signup").and.returnValue();
        this.getCookie=jasmine.createSpy("getCookie");
      });
    });

  });

  beforeEach(inject(function ($rootScope, $compile) {
    el = angular.element("<refugee-register></refugee-register>");
    $compile(el)($rootScope.$new());
    $rootScope.$digest();

    rootScope = $rootScope;

    controller = el.controller("refugeeRegister");

    scope = el.isolateScope() || el.scope();

  }));

  it("should have initialized variables", function () {
    expect(scope.vm).toBeDefined();
  });

  it("should register a user", function () {
    scope.register();
    expect(rootScope.globals.loading).toBe(true);
    expect(authenticationService.signup).toHaveBeenCalled();
  });

});

It should test this module (with logic inside the controller):

function refugeeRegister() {
        var directive = {
          restrict: 'E',
          templateUrl: 'components/register/refugee/refugee_register.html',
          scope: {},
          controller: refugeeRegisterController,
          controllerAs: 'vm',
          bindToController: true
        };

The error in the test is following:

TypeError: undefined is not an object (evaluating 'authenticationService.signup($scope.vm, "REFUGEE").then') in /Users/fabianlurz/refugeehire/app/components/register/refugee/refugee_register.js (line 73)
    register@/Users/fabianlurz/refugeehire/app/components/register/refugee/refugee_register.js:73:60
    /Users/fabianlurz/refugeehire/app/components/register/refugee/refugee_register-spec.js:35:19
PhantomJS 2.1.1 (Mac OS X 0.0.0): Executed 4 of 4 (1 FAILED) (0.004 secs / 0.407 secs)

So how do i return a promise in my mockService (authenticationService)?


回答1:


For hard-coded static resolution it may be

this.signup = jasmine.createSpy("signup").and.returnValue($q.resolve('...');

For dynamic resolution a new promise should be issued on each call:

this.signup = jasmine.createSpy("signup").and.callFake(function () {
  return $q.resolve(...);
});


来源:https://stackoverflow.com/questions/37653702/return-a-promise-in-jasmine-directive-controller

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!