没有平台提供商

时间:2017-11-17 07:11:56

标签: javascript angular angular-material angular-cdk

所以我遇到过这个问题,为Angular 4应用程序进行单元测试

它会在问题标题中一直提供错误。

我试图谷歌它,尝试导入一大堆不同的模块,最后发现这个“平台”的答案可能是来自@angular/browser平台的browserModule。

所以在我的单元测试中,我尝试导入它并声明它但它没有帮助。

任何人都可以帮忙解决这个问题,因为我甚至不确定这个“平台”是什么?

问题:错误中的“平台”究竟是什么以及如何解决?

感谢。

我附上了我的代码如下:

import { ComponentFixture, TestBed, async} from "@angular/core/testing";
import { DebugElement, CUSTOM_ELEMENTS_SCHEMA, PlatformRef} from 
"@angular/core";
import { TeamCreationAssignmentComponent } from "./team-creation-assignment.component";
import { OdmService } from "../../services/odm/odm.service";
import { UserNotificationService } from "../../services/user/user-notification.service";
import { MatSnackBar } from "@angular/material";
import { OVERLAY_PROVIDERS, ScrollStrategyOptions, ScrollDispatcher} from "@angular/cdk/overlay";

describe('Team creation assignment component', () => {
let comp: TeamCreationAssignmentComponent;
let fixture: ComponentFixture<TeamCreationAssignmentComponent>;

let odmServiceSub = {};


beforeEach(async(() => {
    TestBed.configureTestingModule({

        declarations: [TeamCreationAssignmentComponent],
        //imports: [BrowserModule],
        schemas: [CUSTOM_ELEMENTS_SCHEMA],
        providers: [
            {provide: OdmService, useValue: odmServiceSub}, 
            UserNotificationService, 
            MatSnackBar, 
            OVERLAY_PROVIDERS, 
            ScrollStrategyOptions,
            ScrollDispatcher,
        ],
    })
    .compileComponents();
}));

beforeEach(() => {
    fixture = TestBed.createComponent(TeamCreationAssignmentComponent);
    comp = fixture.componentInstance;
});

it('should have defined component', () => {
    expect(comp).toBeDefined();
})

});

2 个答案:

答案 0 :(得分:2)

我使用FocusMonitor遇到了类似的问题(在Angular 5中),并希望根据它来测试组件。反过来,FocusMonitor依赖于Platform。

在您的情况下,它与ScrollDispatcher具有相同的依赖关系。

您需要在TestBed的提供商中添加平台

import { Platform } from '@angular/cdk/platform';

...

providers: [
  {provide: OdmService, useValue: odmServiceSub}, 
  UserNotificationService, 
  MatSnackBar, 
  OVERLAY_PROVIDERS, 
  ScrollStrategyOptions,
  ScrollDispatcher,
  Platform
]

答案 1 :(得分:0)

每当您收到“没有XXX提供商”的消息时,通常表示您在providers方法中遗漏了configureTestingModule数组中的内容。您是否尝试将PlatformRef添加到providers阵列?像这样:

providers: [
    {provide: OdmService, useValue: odmServiceSub}, 
    UserNotificationService, 
    MatSnackBar, 
    OVERLAY_PROVIDERS, 
    ScrollStrategyOptions,
    ScrollDispatcher,
    PlatformRef // <- added here
],

然而,您遗漏的一件事是在第二个detectChanges中拨打beforeEach,它应该如下所示:

beforeEach(() => {
    fixture = TestBed.createComponent(TeamCreationAssignmentComponent);
    comp = fixture.componentInstance;
    fixture.detectChanges(); // <- this is required
});

我要说的一件事是,在我的Angular 4应用程序中,大约有800个单元测试,而其中没有一个使用或需要这个PlatformRef。我认为问题是缺少detectChanges,而不是与这个“平台”有关。