【问题标题】:How to test an Angular component that injects an AngularJS service如何测试注入 AngularJS 服务的 Angular 组件
【发布时间】:2021-07-23 07:19:44
【问题描述】:

我正在运行一个混合 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,但是在它提到的文档中

此助手用于测试服务而不是组件。对于组件 测试你仍然必须引导一个混合应用程序。请参阅 UpgradeModule 或 downgradeModule 了解更多信息。

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

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

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

给出以下错误:

$injector 没有提供者!

【问题讨论】:

    标签: angularjs angular angular-test angular-hybrid


    【解决方案1】:

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

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

    【讨论】:

    • 当然,但这个答案有点过分了。我知道我可以模拟,但是让我们假设服务只提供一些我不需要模拟的常量值。如果这是一个 Angular 服务,它会很好地注入到测试组件中,不需要模拟。问题围绕着在测试期间为组件提供真正的服务。
    • 然后请编辑问题以指定您不想模拟该服务。模拟服务不是“逃避”,这是您通常测试任何组件的方式。
    • 就问题而言只是一个警察。我在问为什么在测试时将 AngularJS 服务注入组件时出错。模拟只是隐藏错误。我想注入 AngularJS 服务。
    • 您是否尝试将myServiceProvider 添加到configureTestingModule 中的providers 数组中?
    猜你喜欢
    • 2020-12-21
    • 2017-06-18
    • 2018-10-27
    • 1970-01-01
    • 2016-12-09
    • 1970-01-01
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    相关资源
    最近更新 更多