我有一个相当简单的单元测试文件,如下所示:
import { CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { Http, HttpModule } from '@angular/http';
import { MockBackend } from '@angular/http/testing';
import { MaterialModule } from '@angular/material';
import { MediaChange, ObservableMedia } from "@angular/flex-layout";
import { PageHeaderComponent } from './page-header.component';
import { UserService } from '../user.service';
import { PreloadService } from '../preload.service';
describe('PageHeaderComponent', () => {
let component: PageHeaderComponent;
let fixture: ComponentFixture<PageHeaderComponent>;
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [PageHeaderComponent],
providers: [
{
provide: Http,
deps: [MockBackend]
},
PreloadService,
UserService
],
imports: [MaterialModule, ObservableMedia],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
});
fixture = TestBed.createComponent(PageHeaderComponent);
component = fixture.componentInstance;
});
it('should be created', () => {
expect(component).toBeTruthy();
});
});
它正在测试一个普通的Angular CLI组件,该组件包含一个用于观察元素可见性断点的订阅:
constructor(public media: ObservableMedia) {
// watch for changes in breakpoint
media.asObservable()
.subscribe((change: MediaChange) => {
// update the header tooltip state
if (change.mqAlias == 'xs') {
this.showHeaderTooltip = false;
}
else {
this.showHeaderTooltip = true;
}
});
}
ngOnInit() {
// check breakpoint and set header tooltip state
if (this.media.isActive('xs')) {
this.showHeaderTooltip = false;
} else {
this.showHeaderTooltip = true;
}
}
它抛出了这个错误:
错误:模块'DynamicTestModule'导入的意外值'ObservableMedia'。请添加@NgModule注释。在http://localhost:9876/_karma_webpack_/polyfills.bundle.js(第6972行) ZoneAwareError @ http://localhost:9876/_karma_webpack_/polyfills.bundle.js:6972:28 的SyntaxError @ http://localhost:9876/_karma_webpack_/vendor.bundle.js:14803:39 http://localhost:9876/_karma_webpack_/vendor.bundle.js:28487:55 forEach @ [本机代码]
....
我在研究中看到了类似的错误报告,但ObservableMedia
没有。我已经尝试将导入添加到app.module.ts,但这没有任何效果。有什么遗漏?
答案 0 :(得分:4)
我认为您应该使用FlexLayoutModule
而不是ObservableMedia
,因为ObservableMedia
只是基本抽象类,而您需要导入角度模块,即使用@NgModule
装饰器装饰的类< / p>