【问题标题】:spyOn with Promise用 Promise 窥探
【发布时间】:2015-06-14 04:54:17
【问题描述】:

我想监视以下函数...但它包含一个承诺...但我收到 TypeError: 'undefined' is not an object (evalating 'modalService.showModal({}, modalOptions) .then')

因为我当然只有 spyOn(modalService,'showModal')

我该如何解释这个承诺呢??

_modalService = {
    close: function (value) { console.log(value) },
    dismiss: function (value) { console.log(value) },
    showModal: function (value) { console.log(value) }
};

spyOn(_modalService, 'close');
spyOn(_modalService, 'dismiss');
spyOn(_modalService, 'showModal');

控制器功能:

user.resetPassword = function () {
            var modalOptions = {
                closeButtonText: 'Cancel',
                actionButtonText: 'Reset',
                headerText: 'Reset Password',
                bodyText: 'Are you sure you want to reset the users password?'
            };

            modalService.showModal({}, modalOptions).then(function (result) {
                if (result === 'ok') {
                    userDataService.resetPassword(user.data).then(function (result) {
                        $scope.$emit('showSuccessReset');
                    });

                };
            });
        };

这是我的单元测试:

it('should allow the users password to be reset', function () {
        var controller = createController();
        controller.resetPassword();
        $httpBackend.flush();
    })

************************更新

所以我把它改成这样:

 //Create a fake instance of the modal instance. TO ensure that the close is called
        _modalService = {
            close: function (value) { console.log(value) },
            dismiss: function (value) { console.log(value) },
            showModal: function (value) { console.log(value) }
        };

        spyOn(_modalService, 'close');
        spyOn(_modalService, 'dismiss');
        spyOn(_modalService, 'showModal').and.callThrough();

        _modalService.showModal = function() {
                var deferred = $q.defer();
                deferred.resolve('Remote call result');
                return deferred.promise;   
            };

说实话,虽然我不确定我能否解释这一点。虽然我了解所有异步的东西......我不确定 jasmine 是如何使用它来使其全部工作的。谁能解释一下流程???另外我觉得语法是错误的......你通常会怎么写这样看起来更好/更干净......??

【问题讨论】:

    标签: angularjs unit-testing jasmine karma-jasmine


    【解决方案1】:

    当您需要模拟一个返回承诺的函数时,您有两种选择:

    1. 返回一个模拟的 Promise(一个类似于 Promise 的对象);
    2. 回报一个真正的承诺。

    我建议使用 #2,因为它更简单,而且您不必担心复制整个 Promise API。换句话说,不值得嘲笑一个 Promise 本身。

    现在关于 Jasmine:当你已经有一个对象(不是模拟)并且你想监视(不是双关语)它的一个方法时,你只需要使用 spyOn。在您的情况下,您的整个对象都是假的,因此您可以改用 jasmine.createSpyObj

    以下示例应该使上述所有内容更加清晰:

    SUT

    app.controller('MainCtrl', function($scope, modal, service) {
      $scope.click = function() {
        modal.show().then(function(result) {
          if (result === 'ok') {
            service.resetPassword();
          }
        });
      };
    });
    

    测试

    describe('Testing a controller', function() {
      var $scope, $q,
          ctrl, modalMock, serviceMock;
    
      beforeEach(function() {
        module('plunker');
    
        modalMock = jasmine.createSpyObj('modal', ['show']);
        serviceMock = jasmine.createSpyObj('service', ['resetPassword']);
    
        inject(function($rootScope, $controller, _$q_) {
          $scope = $rootScope.$new();
          $q = _$q_;
    
          ctrl = $controller('MainCtrl', {
            $scope: $scope,
            modal: modalMock,
            service: serviceMock
          });
        });
      });
    
      it('should reset the password when the user confirms', function() {
        // Arrange
        var deferred = $q.defer();
    
        deferred.resolve('ok');
        modalMock.show.and.returnValue(deferred.promise);
    
        // Act
        $scope.click();
        $scope.$digest(); // Makes Angular resolve the promise
    
        // Assert
        expect(serviceMock.resetPassword).toHaveBeenCalled();
      });
    
      it('should not reset the password when the user cancels', function() {
        // Arrange
        var deferred = $q.defer();
    
        deferred.resolve('cancel');
        modalMock.show.and.returnValue(deferred.promise);
    
        // Act
        $scope.click();
        $scope.$digest(); // Makes Angular resolve the promise
    
        // Assert
        expect(serviceMock.resetPassword).not.toHaveBeenCalled();
      });
    });
    

    Working Plunker

    每个测试中的模拟安排代码可以移动到beforeEach 部分,这样就不会重复。我这样做并不是为了让事情变得简单。

    【讨论】:

      猜你喜欢
      • 2018-08-25
      • 1970-01-01
      • 2017-02-27
      • 2021-01-09
      • 1970-01-01
      • 1970-01-01
      • 2018-10-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多