在AngurJS模拟后端服务器(谷歌表单)(Mock backend server (Google

2019-10-21 07:47发布

我使用AngularJs控制器从形式到谷歌表发送数据。 使用茉莉我写单元测试,这引起了波纹管的问题:

Error: Unsatisfied requests: POST http://localhost:5000/google-form
at Function.$httpBackend.verifyNoOutstandingExpectation 
(.../angular-mocks/angular-mocks.js:1474:13)

谷歌搜索,并通过一些准备后的问题在stackowerflow,我决定后,我并没有为它找到一个解决方案的问题。

这是给你的引用代码:

角控制器

/* global $ */
'use strict';
angular.module('myApp')
  .controller('QuickMessageCtrl', ['$scope', function ($scope) {
    $scope.quickMessageButtonText = 'Send';
    $scope.quickMessage = {
      name: '',
      email: '',
      content: '',
    };

    function setSubmittingIndicators() {
      $scope.quickMessageButtonText = '';
      $scope.submitting = true;
    }

    $scope.postQuickMessageToGoogle = _.throttle(function() {
      setSubmittingIndicators();
      $.ajax({
        url: 'https://docs.google.com/forms/d/MyFormKey/formResponse',
        data: {
          'entry.3'  : $scope.quickMessage.name,
          'entry.1'  : $scope.quickMessage.email,
          'entry.0'  : $scope.quickMessage.content
        },
        type: 'POST',
        dataType: 'jsonp',
        statusCode: {
          200: function (){
            //show succes message;
          }
        }
      });
    }, 500);
  }]);

单元测试代码

'use strict';

describe('Controller: QuickMessageCtrl', function() {
    var $httpBackend, $rootScope, $controller, scope, apiUrl; 

    beforeEach(module('myApp'));

    beforeEach(inject(function($injector) {
        $httpBackend = $injector.get('$httpBackend');
        apiUrl = $injector.get('apiUrl');
        $httpBackend.expect(
            'POST',
            apiUrl + 'google-form',
            {'name': 'test', 'email': 'test@test.com', 'content': 'this is content'}
        ).respond(200);

        $rootScope = $injector.get('$rootScope');
        scope = $rootScope.$new();
        $controller = $injector.get('$controller');
        $controller('QuickMessageCtrl', { $scope: scope });
    }));

    afterEach(function() {
        $httpBackend.verifyNoOutstandingExpectation();
        $httpBackend.verifyNoOutstandingRequest();
    });

    describe('Successful form submit', function() {
        beforeEach(function() {
            scope.quickMessageForm = { $valid: true };
            scope.quickMessage.email = 'test@test.com';
            scope.quickMessage.name = 'test';
            scope.quickMessage.content = 'this is test';
            scope.postQuickMessageToGoogle();
        });

        it('should set submitting indicators on submit', function() {
            expect(scope.quickMessageButtonText).toBe('');
        });

    });
});

Answer 1:

作为@JB Nizet指出你是使用jQuery,而不是角的方法。 事实上,你应该重构你的代码位。

它是一种伟大实践让事情分开,就像从服务控制器。 在你的情况,你所使用的控制器内的服务。 我宁愿建议你创建一个服务,然后在你的控制器导入该服务。 所以基本上这里的代码怎么会是这样的:

调节器

/* global $ */
'use strict';
angular.module('myApp')
  .controller('QuickMessageCtrl', ['$scope', 'MyNewService', function ($scope, MyNewService) {
    $scope.quickMessageButtonText = 'Send';
    $scope.quickMessage = {
      name: '',
      email: '',
      content: '',
    };

    function resetFormData() {
      $('#name').val('');
      $('#email').val('');
      $('#content').val('');
    }

    $scope.postQuickMessageToGoogle = _.throttle(function() {
      setSubmittingIndicators();
      MyNewService.sendQuickMessage(
        $scope.quickMessage.name,
        $scope.quickMessage.email,
        $scope.quickMessage.content
      )
      .success(
        //sucess Message
        //can be as well a function that returns a status code
      )
      .error(
        //error Message
      );
    }, 500);
  }]);

服务

'use strict';
angular.module('myApp')
  .factory('MyNewService', ['$http', function ($http) {
    var myService = {};

    myService.sendQuickMessage = function(name, email, content) {
      $http({
        method: 'JSONP',
        url: 'https://docs.google.com/forms/d/MyFormKey/formResponse?'+
          'entry.3=' + name +
          '&entry.1=' + email +
          '&entry.0=' + content
      });
    };
    return myService;
  }]);

单元测试

'use strict';

describe('Controller: QuickMessageCtrl', function() {
  var $httpBackend, $rootScope, $controller, scope, apiUrl;

  beforeEach(module('myApp'));

  beforeEach(inject(function($injector) {
    $httpBackend = $injector.get('$httpBackend');
    apiUrl = $injector.get('apiUrl');
    $httpBackend.expectJSONP(
      'https://docs.google.com/forms/d/MyFormKey/formResponse?'+
      'entry.3=test'+
      '&entry.1=test@test.com'+
      '&entry.0=thisIsContent'
    ).respond(200, {});

    $rootScope = $injector.get('$rootScope');
    scope = $rootScope.$new();
    $controller = $injector.get('$controller');
    $controller('QuickMessageCtrl', { $scope: scope });
  }));

  describe('form submit', function() {
    var changeStateSpy;
    beforeEach(function() {
      scope.quickMessage.name = 'test';
      scope.quickMessage.content = 'thisIsContent';
      scope.quickMessage.email ='test@test.com';
    });

    afterEach(function(){
      $httpBackend.verifyNoOutstandingExpectation();
      $httpBackend.verifyNoOutstandingRequest();
    });

    it('should set submitting indicators on submit', function() {
      scope.postQuickMessageToGoogle();
      expect(scope.quickMessageButtonText).toBe('');
      $httpBackend.flush();
    });
  });
});


Answer 2:

你的测试说,模拟HTTP后端应在URL收到一个POST

apiUrl + 'google-form'

其中,由于该错误信息,是http://localhost:5000/google-form

但是,你绝不控制器发送一个POST到URL。 它发出了一个POST到https://docs.google.com/forms/d/MyFormKey/formResponse 。 它不采用了棱角分明的$ HTTP服务做到这一点,但确实它的背后,使用jQuery。



文章来源: Mock backend server (Google Forms) in AngurJS