如何注入在app.run函数中使用的模拟angular服务?

How do you inject a mocked angular service that is used in the app.run function?

本文关键字:模拟 服务 angular 函数 run 何注入 注入 app      更新时间:2023-09-26

我已经在我的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的一部分)是一个未知的提供者。你对我该如何解决这个问题有什么好的建议吗?


你能给我们提供住宿吗?
同时,如果你使用的是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);
  });
});

我通过使用约曼脚手架学会了这一点,顺便说一下:)