4

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.

4

1 回答 1

7

如果您想在开发过程中模拟您的后端,只需安装angular-mocks在您的主 html 文件中,将其作为依赖项添加到您的应用程序(angular.module('myApp', ['ngMockE2E']))中,然后模拟您需要的请求。

例如

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
    })
  });

不过要小心,添加ngMockE2E将需要您设置路由,以防您通过 AngularJS 路由进行设置。

例如

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();
  })
于 2013-09-18T22:23:57.517 回答