Mocking angularjs http requests

拜拜、爱过 提交于 2020-01-01 14:09:20

问题


So i have done quite a research already before asking this and none of them is what i want.

I have an app bootstrapped with angular module. The controller inside the module makes some http requests. Now i am unit testing my app for ui and i need to mock the http requests. All the mocking that i have read is done with jasmine, but i don't want to use it.

I want that whenever i open the app, all the requests get mocked. I have already tried angular mock and the backend mocks, none of them workes. And i dont want to prepopulate the scope elements because the code should be deployment ready.


回答1:


If you want to mock your backend during development, just install angular-mocks in your main html file, add it up as a dependency in your application (angular.module('myApp', ['ngMockE2E'])) and then mock the requests you need to.

E.g.

angular.module('myApp')
  .controller('MainCtrl', function ($scope, $httpBackend, $http) {
    $httpBackend.whenGET('test').respond(200, {message: "Hello world"});
    $http.get('test').then(function(response){
      $scope.message = response.message //Hello world
    })
  });

Be wary though, that adding the ngMockE2E will require you to set up your routes in case you do so through AngularJS routing.

E.g.

angular.module('myApp', ['ngMockE2E'])
  .config(function ($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
      })
      .otherwise({
        redirectTo: '/'
      });
  })
  .run(function($httpBackend){
    $httpBackend.whenGET('views/main.html').passThrough();
  })


来源:https://stackoverflow.com/questions/18877593/mocking-angularjs-http-requests

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