如何在 Jasmine 单元测试中获取 TypeScript 中“模块”的定义?

Fla*_*ape 5 javascript angularjs typescript

所以,这真的很愚蠢。但不可能通过谷歌搜索,因为未定义的模块实际上是module. 我在单元测试中消除了所有其他 TS 错误,除了最后一个错误:

main/components/login/loginController.Spec.ts(12,7):错误 TS2304:找不到名称“模块”。

有些人说,“只需包含 angular-mocks.js”,但我已经这样做了,它消除了其他一些错误,但没有消除这个错误。

这是我的参考资料:

/// <reference path="../../typings/angularjs/angular.d.ts" />
/// <reference path="../../typings/jquery/jquery.d.ts" />
/// <reference path="../../typings/d3/d3.d.ts" />
/// <reference path="../../typings/jasmine/jasmine.d.ts" />
/// <reference path="../../typings/angularjs/angular-mocks.d.ts" />
Run Code Online (Sandbox Code Playgroud)

这是一个说明问题的简单测试。

describe('Login Controller Spec', function() {
    beforeEach(function() {
      // uh oh
      module('App');
      inject(function(_$controller_, $rootScope) {
        scope = $rootScope.$new();
        controller = _$controller_;
        navCtrl = controller('loginController', { $scope: scope});
      });

    });

    it('should call init', function(){
         //...
    });
  });
Run Code Online (Sandbox Code Playgroud)

我应该获得其他任何库的定义吗?

Mar*_*cka 4

你可以去

angular.mock.module('App');  
Run Code Online (Sandbox Code Playgroud)

因为源代码

  window.module = angular.mock.module = function() {
    var moduleFns = Array.prototype.slice.call(arguments, 0);
    return isSpecRunning() ? workFn() : workFn;
    /////////////////////
    function workFn() {
      if (currentSpec.$injector) {
        throw new Error('Injector already created, can not register a module!');
      } else {
        var fn, modules = currentSpec.$modules || (currentSpec.$modules = []);
        angular.forEach(moduleFns, function(module) {
          if (angular.isObject(module) && !angular.isArray(module)) {
            fn = function($provide) {
              angular.forEach(module, function(value, key) {
                $provide.value(key, value);
              });
            };
          } else {
            fn = module;
          }
          if (currentSpec.$providerInjector) {
            currentSpec.$providerInjector.invoke(fn);
          } else {
            modules.push(fn);
          }
        });
      }
    }
  };
Run Code Online (Sandbox Code Playgroud)

另一种选择可能是

window['module']('App'); // and maybe also window.module('App');
Run Code Online (Sandbox Code Playgroud)