【问题标题】:Mocking a service thats provided in a component controller in a unit test在单元测试中模拟组件控制器中提供的服务
【发布时间】:2017-12-10 18:15:06
【问题描述】:

这是我在尝试运行单元测试时看到的错误..

Expected undefined to be defined.
TypeError: undefined is not an object (evaluating '$rootScope.$digest')

Module 'ThirdPartyModule' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

任何想法如何模拟 testService 以便我仍然可以编译我的组件?

test.component.spec.ts

import { TestModule } from '../index';

describe('Component: testComponent', () => {

  let $rootScope: angular.IScope;
  let element: angular.IAugmentedJQuery;

  beforeEach(() => {
    angular.mock.module('ui.router');
    angular.mock.module(TestModule.name);
  });

  beforeEach(inject((
    _$rootScope_: angular.IScope,
    $compile: angular.ICompileService,
    _$state_: angular.ui.IStateService) => {
    $rootScope = _$rootScope_;
    element = angular.element('<test></test>');
    element = $compile(element)($rootScope);
  }));

  it('should verify component compiled and rendered template', () => {
    expect(element).toBeDefined();
    $rootScope.$digest();
    let link = element.find('a');
    expect(link.text()).toContain('Click this link!');
  });
});

test.module.ts

import { TestComponent } from './test';

export let TestModule: ng.IModule = angular.module(
  'test', // my module name
  ['ui.router', 'ThirdPartyModule']) // dependencies, ThirdPartyModule contains testService
  .component('test', new TestComponent());

test.component.ts

import { TestComponentController } from './test.component.controller';

export class TestComponent implements ng.IComponentOptions {
  public template: string = '<a ng-if="ctrl.serviceReturned">Click this link!</a>';
  public controller: Function = TestComponentController;
  public controllerAs: string = 'ctrl';

  constructor() {}
}

test.component.controller.ts

export class TestComponentController {

  public serviceReturned: boolean = false;

  constructor(private testService: any) {
    if (this.testService.isDone()) {
      this.serviceReturned = true;
    }
  }
}

TestComponentController.$inject = ['testService'];

【问题讨论】:

  • inject 期间发生错误,导致 $rootScope 和元素未定义,此处未显示。在不知道错误的情况下不可能说出问题所在。如果它被抑制,用 try...catch in beforeEach 捕捉它。
  • 这是错误,我更新了问题.. Module 'ThirdPartyModule' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.
  • 我猜这个错误说明了一切。模块未加载。

标签: angularjs unit-testing angularjs-service


【解决方案1】:

您不需要在 angular.mock.module 中添加“ThirdPartyModule”吗?

【讨论】:

    猜你喜欢
    • 2014-01-16
    • 1970-01-01
    • 2020-04-19
    • 1970-01-01
    • 2014-07-30
    • 1970-01-01
    • 2021-12-23
    • 1970-01-01
    • 2020-01-05
    相关资源
    最近更新 更多