【问题标题】:How do you inject a mocked angular service that is used in the app.run function?如何注入 app.run 函数中使用的模拟 Angular 服务?
【发布时间】:2014-05-19 07:34:08
【问题描述】:

我在我的 Angular 应用程序中添加了一些身份验证逻辑,最初对包装 webapi 的服务的调用在 app.run 函数中执行,如下所示:

myApp.run(function ($rootScope, $location, myService) {

myService.getCurrentUser().then(function (promise) {
    //reroute to either access denied or the start page when access is verified.

});

// register listener to watch route changes
$rootScope.$on("$routeChangeStart", function (event, next, current) {

    //check access
}); 
});

在此之后,我的所有单元测试都失败了,因为我不知道如何在创建应用程序模块之前注入 myService 的模拟版本。我已经将服务和模拟服务分解为一个单独的模块,因此我可以在创建实际应用程序之前创建它。像这样:

   angular.mock.module('ServiceModule');

    angular.mock.module('EArkivApp', function ($provide, myMockedService) {
        $provide.value('myService', myMockedService);
    });

但是这不起作用,它抱怨“myMockedService”(它是 ServiceModule 的一部分)是一个未知的提供者。您对我应该如何解决这个问题有什么好的建议吗?

【问题讨论】:

标签: javascript angularjs unit-testing mocking


【解决方案1】:


你能为我们提供一个 jsfiddle 吗?
同时,如果你使用 Karma,那么你可以使用这样的东西:

/*global  describe, beforeEach, module, inject, it, expect*/
describe('Controller: MyCtrl', function () {
  'use strict';
  // load the controller's module
  beforeEach(module('myApp'));

  var MyCtrl,
      scope,
      modalInstance;

  // Initialize the controller and a mock scope
  beforeEach(inject(function ($controller, $rootScope, myMockedService) {
     scope = $rootScope.$new();
      modalInstance = _$modal_.open({
              templateUrl: 'views/my-template.html'
          });
      MyCtrl = $controller('MyCtrl', {
          $scope: scope, 
          $myMockedService: myMockedService
      });
  }));

  it('should be true', function () {
      expect(true).toBe(true);
  });
});

顺便说一句,我是通过使用 Yeoman 脚手架学到的 :)

【讨论】:

    猜你喜欢
    • 2019-10-25
    • 1970-01-01
    • 2015-12-02
    • 2018-01-10
    • 2013-01-10
    • 2018-11-21
    • 2019-04-18
    • 2017-02-14
    • 2018-04-30
    相关资源
    最近更新 更多