如何测试注入 AngularJS 服务的 Angular 组件

问题描述

我正在运行一个混合角度应用程序。我的大部分服务仍然在 AngularJS 方面。我可以在我的混合应用程序中很好地使用它们。

export function myServiceFactory(i: any): any {
  return i.get('MyService');
}

export const myServiceProvider = {
  provide: MyService,useFactory: myServiceFactory,deps: ['$injector']
};

然后在我的 Angular 应用模块中:

  providers: [
    myServiceProvider,...
  ]

这在运行应用程序时效果很好。但是,我在测试使用这些 AngularJS 服务的任何 Angular 组件时遇到了问题。

@Component({
  selector: 'my-component',templateUrl: './my-component.html',styleUrls: ['./my-component.scss'],})
export class MyComponent {

  constructor(@Inject(MyService) private myService: any) {} 
  ...
}

然后是一个简单的测试,看看我是否可以创建组件:

describe('MyComponent',() => {
  let component: MyComponent;
  let fixture: ComponentFixture<MyComponent>;

  beforeEach(async(() => {
    Testbed.configureTestingModule({
      declarations: [MyComponent ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = Testbed.createComponent(MyComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  fit('should create',() => {
    expect(component).toBeTruthy();
  });
});

运行测试时出现以下错误

InjectionToken MyService 没有提供者!

我尝试研究使用这个:https://angular.io/api/upgrade/static/testing/createAngularTestingModule,但是在它提到的文档中

此帮助程序用于测试服务而非组件。对于组件 测试您仍然必须引导混合应用程序。请参阅升级模块或 downgradeModule 了解更多信息。

然而,深入研究 UpgradeModule 和 downgradeModule,实际上没有任何关于如何引导混合应用程序来测试组件的文档。

尝试在测试模块中使用提供者提供,

Testbed.configureTestingModule({
  declarations: [ObservationListItemComponent ],providers: [mapServiceProvider]
})
.compileComponents();

给出以下错误

$injector 没有提供程序!

解决方法

就像测试注入 Angular 服务的组件一样,您应该使用设置测试模块中的 providers 数组注入 AngularJs 服务的模拟。

let myMockService = { fakeMethod: () => {} };

TestBed.configureTestingModule({
    declarations: [MyComponent],providers: [provide: MyService,useValue: myMockService],});