Angularjs配置为使用模拟

时间:2014-02-11 08:14:36

标签: angularjs

如何配置角度应用以在一台服务器上使用存根服务而在另一台服务器上使用存根服务?我想在一个超级便宜的PHP网络服务器上托管我的应用程序,以便向利益相关者进行演示。我可以存根外部休息服务,但我没有写任何PHP多年,并不是真的想。我更喜欢使用也可用于端到端测试的存根角度服务。我想用配置做而不是改变任何代码...

1 个答案:

答案 0 :(得分:1)

您可以在$provide.value(...)块中使用config(...)来实现此目的:

angular.module('stub', []). // <- module that holds mock service
  factory('appServiceMock', function() { // <- mock for appService that will be defined in app module
    return {
      getName: function() {
        return 'Mock Service';
      }
    }
  });

angular.module('app', ['stub']). // <- define app module depends on stub module
  factory('appService', function() {
    return {
      getName: function() {
        return 'Real Service';
      }
    }
  }).
  config(function($provide, appServiceMockProvider) { // <- only providers and constants may be injected to config block. appServiceMockProvider - is created by Angular automatically when you define factory('appServiceMock', ...).
    $provide.value('appService', appServiceMockProvider.$get()); // <- get mock service from provider
  }).
  controller('appController', function($scope, appService) { // <- no changes in controller definition 
    $scope.name = appService.getName(); // <- will return 'Mock Service'
  });

Plunker:http://plnkr.co/edit/b3vIh6aCGNami2m0Bgrz?p=preview

对于您的测试,您可以执行相同的操作(注意:您应该包含angular-mocks.js以便在测试中使用module(...)inject(...) ) :

describe('Test Scope', function() {

    beforeEach(function(){
        module('app', function($provide) {
            $provide.value('appService', {
                name: 'Mock Service'
            });
        });
    });

    it('should do something', inject(function(appService) {
        expect(appService.name).toBeDefined();
    }));
});

除此之外,AngularJS还为其服务提供了大量的模拟。你只需要包含angular-mocks.js,它将覆盖一些角度内置服务,并将添加一些其他有用的东西。例如,如果使用$http访问远程REST服务,则可以使用$httpBackend来模拟它们:

it('should check REST service', inject(function($httpBackend, appServiceThatUseHttp) {
    var response;
    $httpBackend.resetExpectations();
    $httpBackend.expect('GET', 'http://www.test.com/v1/things').respond({things: ['thing 1', 'thing 2']});
    response = appServiceThatUseHttp.getThings(); // <- Assume that service puts parsed response body into it's property named data
    $httpBackend.flush();
    expect(response.data.things.length).toBe(2);
}));